計算一定範圍內素數個數的演算法

2021-09-30 13:39:45 字數 2625 閱讀 8063

問題:給定乙個大整數n,計算開區間(1,n)的素數有多少?

#include

#include

#include

#include

#include

#undef true

#define true 1

#undef false

#define false 0

typedef

int bool32;

// a不能整除小於等於根號a的所有整數,則必為素數

void

chooseprimenumber_slow

(int dwtestsize)

memset

(pbnumber,

0, dwtestsize*

sizeof

(int))

;int dwindex, dwloop =0;

*(pbnumber+2)

= true;

for(dwindex=

3; dwindex}// 計算素數個數

int dwnum =0;

for(dwindex=

2; dwindex)printf

("less than %d, there are %d prime number!\n"

, dwtestsize, dwnum)

;delete

pbnumber;

return;}

// 素數篩選法

void

chooseprimenumber_fast

(int dwtestsize)

memset

(pbnumber,

0, dwtestsize*

sizeof

(int))

;int dwindex, dwloop =0;

*(pbnumber+2)

= true;

for(dwindex=

3; dwindex)for

(dwindex=

3; dwindex<=

(int

)sqrt((

double

)dwtestsize)

; dwindex++)}

// 計算素數個數

int dwnum =0;

for(dwindex=

2; dwindex)printf

("less than %d, there are %d prime number!\n"

, dwtestsize, dwnum)

;delete

pbnumber;

// free(pbnumber);

return;}

///int

main()

return0;

}

less than 10000, there are 1229 prime number!

[0] method chooseprimenumber_slow spend 2 ms.

less than 10000, there are 1229 prime number!

[0] method chooseprimenumber_fast spend 0 ms.

less than 100000, there are 9592 prime number!

[1] method chooseprimenumber_slow spend 41 ms.

less than 100000, there are 9592 prime number!

[1] method chooseprimenumber_fast spend 1 ms.

less than 1000000, there are 78498 prime number!

[2] method chooseprimenumber_slow spend 973 ms.

less than 1000000, there are 78498 prime number!

[2] method chooseprimenumber_fast spend 32 ms.

less than 10000000, there are 664579 prime number!

[3] method chooseprimenumber_slow spend 23846 ms.

less than 10000000, there are 664579 prime number!

[3] method chooseprimenumber_fast spend 398 ms.

less than 100000000, there are 5761455 prime number!

[4] method chooseprimenumber_slow spend 643918 ms.

less than 100000000, there are 5761455 prime number!

[4] method chooseprimenumber_fast spend 4695 ms.

press any key to continue

從執行結果顯而易見,演算法2效率要遠遠高於演算法1。

C C 查詢一定範圍內的素數(篩法)

本文 於 由於乙個合數總是可以分解成若干個質數的乘積,那麼如果把質數 最初只知道2是質數 的倍數都去掉,那麼剩下的就是質數了。例如要查詢100以內的質數,首先2是質數,把2的倍數去掉 此時3沒有被去掉,可認為是質數,所以把3的倍數去掉 再到5,再到7,7之後呢,因為8,9,10剛才都被去掉了,而10...

C C 查詢一定範圍內的素數(篩法)

本文 於 由於乙個合數總是可以分解成若干個質數的乘積,那麼如果把質數 最初只知道2是質數 的倍數都去掉,那麼剩下的就是質數了。例如要查詢100以內的質數,首先2是質數,把2的倍數去掉 此時3沒有被去掉,可認為是質數,所以把3的倍數去掉 再到5,再到7,7之後呢,因為8,9,10剛才都被去掉了,而10...

YTU OJ 2460 一定範圍內特定素數和

求一定範圍內 m,n 特定素數的和 特定素數指含有數字3的素數,比如3,13,31等 第一行輸入乙個數t代表測試資料組數,隨後的t行每行包含兩個數m,n代表一定的範圍 0輸出有t行,每行包含乙個數,輸出相應的特定素數的和 2 14 3 16 include include include defin...