- /** Goldbach conjecture verification
- *
- * \\input.txt //even numbers
- * \\output.txt //results
- *哥德巴赫猜想验证,输入多个大于2的偶数,计算这些偶数可表示多少对素数的和。
- *输入文件,每行一个偶数;输出文件,每行一个结果。
- */
- #include <iostream>
- #include <fstream>
- using namespace std;
- bool isPrime(int num); //素数判断函数声明
- int countPair(int em); //求解函数声明
- int main()
- {
- char* buffer = new char(80);
- ifstream infile("input.txt");
- ofstream outfile("output.txt");
- if(infile.fail()||outfile.fail())
- {
- cout<<"读取文件失败!"<<endl;
- return 0;
- }
- cout<<"输入\\t输出"<<endl;
- while(infile.getline(buffer,80))
- {
- int em=0;
- int result;
- for(int i=0;i<80;i++)
- {
- int x=0;
- if(buffer[i]!=NULL)
- {
- x=(int)buffer[i]-48;
- em=em*10+x;
- }
- else
- break;
- }
- if(em==0)
- break;
- result=countPair(em);//计算结果
- if(result<0)
- {
- cout<<em<<"\\t该数据不符合要求!"<<endl;
- outfile<<"该数据不符合要求"<<endl;
- }
- else
- {
- cout<<em<<"\\t"<<result<<endl;
- outfile<<result<<endl;
- }
- }
- cout<<endl;
- return 0;
- }
- //素数判断函数定义
- bool isPrime(int num)
- {
- if(num<2)
- return false;
- for(int i=2;i<num;i++)
- {
- if(num%i==0)
- return false;
- }
- return true;
- }
- //求解函数定义
- int countPair(int em)
- {
- int cfp=0;
- if(em<=2||em%2!=0)
- return -1;
- for(int i=2;i<=(em/2);i++)
- {
- if(isPrime(i)&&isPrime(em-i)) //
- cfp++;
- }
- return cfp;
- }
- //该片段来自于http://www.codesnippet.cn/detail/1808201410216.html
来源: http://www.codesnippet.cn/detail/1808201410216.html