DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
質數與雙生質數
// description of your code here
#include <iostream>
#include <cmath>
#include <ctime>
using namespace std;
bool CheckPrime(int n)
{
bool flag = true;
int i;
for(i=2; i<=sqrt(n); i++)
if(n % i == 0)
{
flag = false;
break;
}
return flag;
}
bool CheckTwinPrime(int n, bool isP[])
{
if(isP[n] && isP[n+2])
return true;
else return false;
}
void main()
{
srand(time(NULL));
rand();
int n = (rand() % 2001) + 10000;
bool *isP = new bool[n];
int i, cnt=0;
isP[0] = false;
for(i=2; i<=n; i++)
{
if(CheckPrime(i))
isP[i-1] = true;
else isP[i-1] = false;
}
cout<<"N值="<<n;
cout<<" ,變生質數為 ";
for(i=1; i<=n; i++)
if(CheckTwinPrime(i, isP))
{
cnt++;
cout<<"("<<i+1<<" ,"<<i+3<<") ";
}
cout<<" ,共有"<<cnt<<"å°!";
cout<<endl;
system("pause");
}





