在 文章中,對小素數的列舉進行了**,今天發現,由於小素數的倍數比較多,過濾所用時間較長。所以先對奇數進行初步過濾,可以達到提速的效果,繼續改進如下:
private sub command1_click()
dim p() as long
dim i as long
for i = 2 to 8
prime 10 ^ i, p
next
end sub
sub prime(byval n as long, byref prime() as long)
redim prime(5761495) '10^8以內的素數個數
dim i as long, temp as long, half as long, p as long, pcount as long, mytime as long, msg as string
mytime = timer '計時
'把所有素數分成49種情況 210n+1,210n+11,210n+13,210n+17,210n+19,210n+23,210n+29,210n+31,210n+37,210n+41,210n+43,210n+47,210n+53,210n+59,210n+61,210n+67,210n+71,210n+73,210n+79,210n+83,210n+89,210n+97,210n+101,210n+103,210n+107,210n+109,210n+113,210n+121,210n+127,210n+131,210n+137,210n+139,210n+143,210n+149,210n+151,210n+157,210n+163,210n+167,210n+169,210n+173,210n+179,210n+181,210n+187,210n+191,210n+193,210n+197,210n+199,210n+209,210n+211
dim a(1 to 209) as byte
a(1) = 10
a(11) = 2
a(13) = 4
a(17) = 2
a(19) = 4
a(23) = 6
a(29) = 2
a(31) = 6
a(37) = 4
a(41) = 2
a(43) = 4
a(47) = 6
a(53) = 6
a(59) = 2
a(61) = 6
a(67) = 4
a(71) = 2
a(73) = 6
a(79) = 4
a(83) = 6
a(89) = 8
a(97) = 4
a(101) = 2
a(103) = 4
a(107) = 2
a(109) = 4
a(113) = 8
a(121) = 6
a(127) = 4
a(131) = 6
a(137) = 2
a(139) = 4
a(143) = 6
a(149) = 2
a(151) = 6
a(157) = 6
a(163) = 4
a(167) = 2
a(169) = 4
a(173) = 6
a(179) = 2
a(181) = 6
a(187) = 4
a(191) = 2
a(193) = 4
a(197) = 2
a(199) = 10
a(209) = 2
dim x() as byte
redim x(1 to n)
'the first 10 prime
prime(0) = 2
prime(1) = 3
prime(2) = 5
prime(3) = 7
prime(4) = 11
prime(5) = 13
prime(6) = 17
prime(7) = 19
prime(8) = 23
prime(9) = 29
pcount = 9
p = 11
do while p * p <= n
temp = p * p
for i = temp to n step 2 * p 'p的倍數
x(i) = 1 '設為1表示棄去
next
again:
p = p + a(p mod 210)
if x(p) = 1 then goto again
loop
i = 31
do while i < n
if x(i) = 0 then
pcount = pcount + 1
prime(pcount) = i '賦值
end if
i = i + a(i mod 210)
loop
redim preserve prime(pcount) '重設定陣列大小節省空間
msg = format(timer - mytime, "0.0000") & " seconds."
debug.print "n=" & n & ",prime count=" & pcount + 1 & ", the calulating time is " & msg
end sub
返回:n=1000,prime count=168, the calulating time is 0.011 seconds.
n=10000,prime count=1229, the calulating time is 0.031 seconds.
n=100000,prime count=9592, the calulating time is 0.072 seconds.
n=1000000,prime count=78498, the calulating time is 0.1033 seconds.
n=10000000,prime count=664579, the calulating time is 0.7756 seconds.
n=100000000,prime count=5761455, the calulating time is 11.0334 seconds.
可以看到,篩選10000000內所有素數並賦值到乙個陣列,僅僅需要0.77秒鐘,速度大大提高。
素數的快速列舉 二
半年前曾在我的blog發過一篇文章 http blog.csdn.net northwolves archive 2005 04 18 351998.aspx 對素數的快速列舉進行了初步 隨後的討論在http community.csdn.net expert topic 4395 4395751....
等差素數列(列舉 素數篩選法)
題目如下 2,3,5,7,11,13,是素數序列。類似 7,37,67,97,127,157 這樣完全由素數組成的等差數列,叫等差素數數列。上邊的數列公差為30,長度為6。這是數論領域一項驚人的成果!2004年,格林與華人陶哲軒合作證明了 存在任意長度的素數等差數列。有這一理論為基礎,請你借助手中的...
快速判斷素數
首先看乙個關於質數分布的規律 大於等於5的質數一定和6的倍數相鄰。例如5和7,11和13,17和19等等 證明 令x 1,將大於等於5的自然數表示如下 6x 1,6x,6x 1,6x 2,6x 3,6x 4,6x 5,6 x 1 6 x 1 1 可以看到,不在6的倍數兩側,即6x兩側的數為6x 2,...