素數的快速列舉 二

2021-04-02 02:18:24 字數 2466 閱讀 5448

半年前曾在我的blog發過一篇文章(http://blog.csdn.net/northwolves/archive/2005/04/18/351998.aspx),對素數的快速列舉進行了初步**,隨後的討論在http://community.csdn.net/expert/topic/4395/4395751.xml?temp=.9719355進行,kitegirl(小仙妹)jiangsheng(蔣晟.m**vp2004jan)給予了很大的啟發,特此將改進後的**與大家共享。

sub prime(byval n as long, byref prime() as long)

redim prime(5761495) '10^8以內的素數個數

dim a() as byte, i as long, temp as long, half as long, p as long, pcount as long, mytime as long, k as integer

mytime = timer '計時

half = n / 2

redim a(1 to half)

'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 = 3

do while p * p <= n

temp = p * p

for i = temp to n step 2 * p 'p的倍數

a(i / 2) = 1 '設為1表示棄去

next

again:

p = p + 2

if a(p / 2) = 1 then goto again

loop

'把素數分成8種情況:30n+1,30n+7,30n+11,30n+13,30n+17,30n+19,30n+23,30n+29

dim s(7) as byte

s(0) = 0

s(1) = 3

s(2) = 5

s(3) = 6

s(4) = 8

s(5) = 9

s(6) = 11

s(7) = 14

for i = 15 to half step 15

for j = 0 to 7

temp = i + s(j)

if temp > half then exit for: exit for

if a(temp) = 0 then

pcount = pcount + 1

prime(pcount) = 2 * temp + 1 '賦值

end if

next

next

redim preserve prime(pcount) '重設定陣列大小節省空間

debug.print "n=" & n & ",prime count=" & pcount & ", the calulating time is " & timer - mytime & " s"

end sub

private sub command1_click()

dim p() as long

dim i as long

for i = 2 to 8

prime 10 ^ i, p

next

end sub

返回:n=100,prime count=25, the calulating time is 0.0000 seconds.

n=1000,prime count=168, the calulating time is 0.0000 seconds.

n=10000,prime count=1229, the calulating time is 0.0000 seconds.

n=100000,prime count=9592, the calulating time is 0.0002 seconds.

n=1000000,prime count=78498, the calulating time is 0.2269 seconds.

n=10000000,prime count=664579, the calulating time is 2.0719 seconds.

n=100000000,prime count=5761455, the calulating time is 15.2344 seconds.

當然,跟c語言的速度還是有一定距離的,但基本上可以滿足計算的需要了,編譯成exe檔案後還可以更快些。

素數的快速列舉 三

在 文章中,對小素數的列舉進行了 今天發現,由於小素數的倍數比較多,過濾所用時間較長。所以先對奇數進行初步過濾,可以達到提速的效果,繼續改進如下 private sub command1 click dim p as long dim i as long for i 2 to 8 prime 10 ...

素數的快速判斷方法

大於等於5的素數與6的倍數相鄰 所有自然數可以用集合a 表示,其中n 0,顯然,子集b 內的元素都不是素數,所以只有6n 1和6n 5可能是素數,素數一定可以用6n 1和6n 5其中的一個形式表示,即大於等於5的素數與6的倍數相鄰 上面說到大於或等於5的素數一定可以用6n 1或者6n 5來表示,在判...

關於素數表的製作以及利用素數表的快速素數判斷方法

第一次寫部落格,紀念我轉行2星期。昨天晚上刷codewar的題目,心血來潮想能不能用歐幾里得篩法重新做快速素數判斷方法呢?這個方法雖然說空間複雜度要遠遠高於試除法。voidgenerateprime intn loop for primelist index 0 primelist index pr...

查詢特定的合數 求素數 列舉

時間限制 1 sec 記憶體限制 128 mb 題目描述 自然數中除了能被1和本身整除外,還能被其他數整除的數叫合數。每個合數都可以寫成幾個質數相乘的形式,這幾個質數都叫做這個合數的質因數。比如8 2 2 2,2就是8的質因數。在1 n n 200000 按從小到大順序排列的自然數序列中,查詢第m個...

利用構建素數表的方法快速得到素數

今天在東華oj上做了一道題,基礎部分第40題 分拆素數和,涉及到素數。我覺得題目不難,我是這樣寫的 t40 分拆素數和 演算法概述 對於一個偶數num,從2到num 2 1依次測試拆分是否滿足要求 include include 判斷是否為素數 int isprim int x return 1 i...