Monday, March 14, 2005
Prime Numbers table and Insert Script
Here is the script to create the Prime Numbers table and populate the first 1000 Prime numbers.
CREATE TABLE dbo.PrimeNumbers(Number bigint PRIMARY KEY)
GO
--Insert First 1000 Prime Numbers
DECLARE @num bigint
DECLARE @cnt int
DECLARE @isPrime bit
DECLARE @nsqrt int
DECLARE @divisor int
INSERT INTO PrimeNumbers VALUES(2) -- First Prime Number
SET @num = 3 --Next Prime Number
SET @cnt = 1 --One row already inserted.
WHILE @cnt <>
BEGIN
SET @isPrime = 1 -- Be Optimistic ;)
SET @nsqrt = FLOOR(SQRT(@num))
SET @divisor = 3
WHILE @divisor <= @nsqrt
BEGIN
IF @num % @divisor = 0
BEGIN
SET @isPrime = 0
BREAK
END
SET @divisor = @divisor + 2
END
IF @isPrime = 1
BEGIN
SET @cnt = @cnt + 1
INSERT INTO PrimeNumbers VALUES(@num)
END
SET @num = @num+2
END
--SELECT * FROM PrimeNumbers
Here is the script to create the Prime Numbers table and populate the first 1000 Prime numbers.
CREATE TABLE dbo.PrimeNumbers(Number bigint PRIMARY KEY)
GO
--Insert First 1000 Prime Numbers
DECLARE @num bigint
DECLARE @cnt int
DECLARE @isPrime bit
DECLARE @nsqrt int
DECLARE @divisor int
INSERT INTO PrimeNumbers VALUES(2) -- First Prime Number
SET @num = 3 --Next Prime Number
SET @cnt = 1 --One row already inserted.
WHILE @cnt <>
BEGIN
SET @isPrime = 1 -- Be Optimistic ;)
SET @nsqrt = FLOOR(SQRT(@num))
SET @divisor = 3
WHILE @divisor <= @nsqrt
BEGIN
IF @num % @divisor = 0
BEGIN
SET @isPrime = 0
BREAK
END
SET @divisor = @divisor + 2
END
IF @isPrime = 1
BEGIN
SET @cnt = @cnt + 1
INSERT INTO PrimeNumbers VALUES(@num)
END
SET @num = @num+2
END
--SELECT * FROM PrimeNumbers