在100到1000中验证哥德巴赫猜想(任何一个不小于6的偶数都能分解为两个素数之和)。最需要注意的是参数生存期的问题。
Code
/**//*算法说明:将偶数n分为3和(n-3),然后验证它们是否为素数,如果不都是素数,则小的数加2,大的数减2,继续判断。 */
#include <iostream>
#include <cmath>
using namespace std;
int IsPrim(double x) //判断x是否为质数,在VSTS2008中sqrt()中的参数的可用类型中没有int型
{
int i=2;
for (;i<=sqrt(x);i++)
{
if ((int)x%i==0)
return 0;
return 1;
}
}
int Operation(int n)
{
int x=3;
int y=n-3;
while((!IsPrim(x)) || (!IsPrim(y)))
{
x+=2;
y-=2;
if(x>y)
{
cout << "Error!" << endl;
return -1;
}
}
cout << n << "=" << x << "+" << y << endl;
return 0;
}
int main()
{
int n=100;
for(;n<=1000;n+=2)
Operation(n);
return 0;
}
/**//*算法说明:将偶数n分为3和(n-3),然后验证它们是否为素数,如果不都是素数,则小的数加2,大的数减2,继续判断。 */
#include <iostream>
#include <cmath>
using namespace std;
int IsPrim(double x) //判断x是否为质数,在VSTS2008中sqrt()中的参数的可用类型中没有int型
{
int i=2;
for (;i<=sqrt(x);i++)
{
if ((int)x%i==0)
return 0;
return 1;
}
}
int Operation(int n)
{
int x=3;
int y=n-3;
while((!IsPrim(x)) || (!IsPrim(y)))
{
x+=2;
y-=2;
if(x>y)
{
cout << "Error!" << endl;
return -1;
}
}
cout << n << "=" << x << "+" << y << endl;
return 0;
}
int main()
{
int n=100;
for(;n<=1000;n+=2)
Operation(n);
return 0;
}