Implementing prime calculation in SQL SERVER 2005

Source: Internet
Author: User
Tags end insert sql

I will present a challenge, who can use Sqlseerver to propose the best method of calculating primes, I have used a new characteristic CTE and some TSQL implementations, but both are not ideal, the former (CTE) has limitations, while the latter (TSQL) produces 1 million prime numbers in 7 minutes. Can you do better? Here are some of my Code passages

(TSQL Implementation)

set nocount on
declare @prime table (prime int not null primary key)
--insert into @prime values (2)
--insert into @prime values (3)
--insert into @prime values (5)
--insert into @prime values (7)
--insert into @prime values (11)
declare @number int, @pc int
set @number = 13
set @pc = 1
while @pc < 1000000
begin
if not exists (select 1 from @prime where @number % prime = 0 and prime < sqrt(@number) )
begin
insert into @prime select @number
set @pc = @pc +1
end
set @number = @number
+ case when @number %2 = 1 then 2
when @number %3 = 2 then 2
when @number %5 = 4 then 2
when @number %7 = 6 then 2
when @number %11 = 10 then 2
else 1 end
end
select @pc

And

(CTE Implementation)

with seq
as( select 13 number
union all
select s.number
+ case when s.number %2 = 1 then 2
when s.number %3 = 2 then 2
when s.number %5 = 4 then 2
when s.number %7 = 6 then 2
when s.number %11 = 10 then 2
else 1 end
from seq s
where number < 32767
)
, prime as (
select s.number
from seq s
where not exists ( select 1 from seq s2 where s2.number < s.number and (s.number) % s2.number = 0)
)
select *
from prime
option (MAXRECURSION 32767)


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.