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

求一小程序 急该怎么解决

2012-02-06 
求一小程序 急!!!!从键盘输入一个正整数limit(limit 6),验证从6-n之间的所有偶数都可以分解为两个素数之

求一小程序 急!!!!
从键盘输入一个正整数limit(limit> =6),验证从6-n之间的所有偶数都可以分解为两个素数之和

[解决办法]
#include <stdio.h>
#include <math.h>
void main()
{
int a,b,c,d;
printf( "Please input a number: ");
scanf( "%d ",&a);
for(b=3;b <=a/2;b+=2)
{
for(c=2;c <=sqrt(b);c++)
if(b%c==0)
break;
if(c> sqrt(b))
{
d=a-b;
for(c=2;c <=sqrt(d);c++)
if(d%c==0)
break;
if(c> sqrt(d))
{
printf( "%d=%d+%d\n ",a,b,d);
break;
}
}
}

}

把输入输出换成C++的方式就OK了。。。
[解决办法]
#include <iostream>
#include <math.h>

using namespace std;

int main()
{
int limit;
int p1,p2;
int i,flag=0;
cout < < "Please input the number(number> =6): ";
cin> > limit;
while(limit < 6)
{
cout < < "input error! " < <endl;
cout < < "Please input the number(number> =6): ";
cin> > limit;
}
for(p1=3; p1 <limit/2; p1++)
{
for(i=2; i <=sqrt(p1); i++)
{
if(p1%i ==0)
break;
}
if(i> sqrt(p1))//第一个素数
{
p2 = limit - p1;
for(i=2; i <= sqrt(p2); i++)
{
if(p2%i == 0)
break;
}
if(i > sqrt(p2))//第二个素数
{
cout < < "DONE " < <endl;
cout < <limit < < " = " < <p1 < < " + " < <p2 < <endl;
flag = 1;
break;
}
}
}
if(flag == 0) //不能分解为素数之和
cout < < "Cannot be divide into two primes! " < <endl;
system( "pause ");
return 0;
}

热点排行