若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。
題目連結 http://zerojudge.tw/ShowProblem?problemid=a121。
維基百科上
質數的定義為:
Sieve of Eratosthenes演算法(底下文字取自
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes):
Input: an integer n > 1.
Let A be an array of Boolean values, indexed by integers 2 to n,
initially all set to true.
for i = 2, 3, 4, ..., not exceeding √n:
if A[i] is true:
for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n:
A[j] := false.
Output: all i such that A[i] is true.
筆者先用Sieve of Eratosthenes演算法求出100000000以下的所有質數的對照表,接著再用迴圈檢查 [a,b] 範圍內有多少個質數。
程式碼:
#include <cmath>
#include <vector>
#include <iostream>
using namespace std;
#define NUM 100000001
int main(int argc, char** argv) {
vector<bool> isP;
long cnt;
long a, b;
for(int i = 0; i < NUM; i++)
isP.push_back(true);
isP[0] = false;
isP[1] = false;
for(long i = 2; i <= 10000; i++)
{
if(isP[i])
{
for(long j = i * i; j < NUM; j += i)
isP[j] = false;
}
}
while(cin >> a >> b)
{
cnt = 0;
for(long i = a; i <= b; i++)
{
if(isP[i]) cnt++;
}
cout << cnt << endl;
}
return 0;
}