首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

c++新手,验证哥德巴赫猜想

2013-11-29 
c++新手求助,验证哥德巴赫猜想题目要求建立一个判断素数的函数is_prime 我的程序编写后输出数值中还是有非

c++新手求助,验证哥德巴赫猜想
题目要求建立一个判断素数的函数is_prime 
我的程序编写后输出数值中还是有非素数,一下子找不出哪里错了,刚学c++,求高手帮我检查下。
#include<iostream>
using namespace std;
bool is_prime(long int a)
{  
long int x=1;
   for(;x<=(a/2);x++)
   {
   if (a%x==0)
   {
   return 1;
   break;
   }
   
   
   if (x>=(a/2)) return 0;
   
   else return 1;
   }
}
int main()
{
int x,y,z;
cout<<"请输入一个大于2的偶数:";
cin>>x;
if (x%2!=0||x<2)

cout<<"输入的数据有误";
}
else 
{cout<<"可以分解为以下两个素数相加的情况:"<<endl;                           
     for (y=2;is_prime(y)&&y>0;y++)
     if (x-y>0&&is_prime(x-y))
     
     cout<<y<<" "<<x-y<<endl;
}

return 0;
} c++?哥德巴赫
[解决办法]
1. 循环从 2 开始, 不要从 1 开始.
2. return 1; 后面跟 break; 没有意义, 不会被执行到.
3. 能整出的就不是素数, if (a%x==0) 后面应该 return 0, 不是 return 1;
4.  if (x>=(a/2))  ... else ...  这是要干啥? 这样 return 后 for 循环也没有任何意义了.

修改后的:


bool is_prime(long int a)
{  
long int x=2;
for(;x<=(a/2);x++)
{
if (a%x==0)
{
return 0;
}
}

return 1;
}

热点排行