写一个程序验证歌德巴赫猜想:一个不小于6的偶数可以表示为两个素数之和,即6=3+3,8=3+5,10=3+7,……,在主函数中输入一个不小于6的偶数n,然后调用函数gotbaha,在该函数中再调用prime函数,prime函数是判断一个数是否为素数(是返回1,不是返回0)。在gotbaha函数中输出以下形式的结果:
34=31+3
提示:假设偶数n=a+b,分别判断a和b是否为素数(a和b不可能是偶数),a只需是在3~n/2中的某个素数,若a是素数,且b=n-a也是素数,则输出结果。
#include<iostream>
#include<vector>
using std::cout;
using std::cin;
using std::endl;
using std::vector;
int main()
{
vector<int> gotbaha(int);
bool prime(int);
cout << "please input a number:";
int x;
cin >> x;
vector<int> result = gotbaha(x);
for(vector<int>::size_type t=0;t!= result.size(); t++)
cout << x << '=' << result[t] << '+' << x - result[t] << endl;
system("pause");
return 0;
}
vector<int> gotbaha(int x)
{
vector<int> result;
bool prime(int);
for (int a = 3; a <= x / 2; a += 2)
{
if (prime(a) && prime(x - a))
result.push_back(a);
}
return result;
}
bool prime(int n)
{
int t = 2;
for (;t!=n;t++)
{
if (n%t == 0)
break;
}
if (t == n)
return 1;
else
return 0;
}