[Project Euler] 來做尤拉專案練習題吧: 題目007
周銀輝
問題描述:
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10001st prime number?
問題分析:
如果要大量求素數的話,比較快速的方法是“篩法(sieve)”。其速度很快,但其需要知道上限,這個題目沒有給,猜吧,我猜110000(實際上,110000下面有10453個素數)。
篩法求素數可以如下描述(抄自維基百科):
Eratosthenes' method:
- Create a list of consecutive integers from two to n: (2, 3, 4, ..., n).
- Initially, let p equal 2, the first prime number.
- Strike from the list all multiples of p less than or equal to n. (2p, 3p, 4p, etc.)
- Find the first number remaining on the list after p (this number is the next prime); replace p with this number.
- Repeat steps 3 and 4 until p2 is greater than n.
- All the remaining numbers in the list are prime.
參考程式碼:
#define SZ 110000
char buffer[SZ];
void iniBuffer()
{
buffer[0] = buffer[1] = 'F';
int p = sqrt(SZ);
int i, j;
for(i=2; i<=p; i++)
{
if(buffer[i]!='F')
{
for(j=2; j*i<SZ; j++)
{
buffer[j*i]='F';//標記其不是素數
}
}
}
}
在buffer中沒有被標記為'F'的元素所對應的陣列下標都是素數。這樣建立素數表將會是後面很多題目的基礎。