C++验证歌德巴赫猜想

       在100到1000中验证哥德巴赫猜想(任何一个不小于6的偶数都能分解为两个素数之和)。最需要注意的是参数生存期的问题。

ContractedBlock.gif ExpandedBlockStart.gif Code
ExpandedBlockStart.gifContractedBlock.gif/**//*算法说明:将偶数n分为3和(n-3),然后验证它们是否为素数,如果不都是素数,则小的数加2,大的数减2,继续判断。 */
None.gif
None.gif#include 
<iostream>
None.gif#include 
<cmath>
None.gif
using namespace std;
None.gif
None.gif
int IsPrim(double x)    //判断x是否为质数,在VSTS2008中sqrt()中的参数的可用类型中没有int型
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
int i=2;
InBlock.gif    
for (;i<=sqrt(x);i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
if ((int)x%i==0)
InBlock.gif            
return 0;
InBlock.gif       
return 1;
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
None.gif
int Operation(int n)
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
int x=3;
InBlock.gif    
int y=n-3;
InBlock.gif    
while((!IsPrim(x)) || (!IsPrim(y)))
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        x
+=2;
InBlock.gif        y
-=2;
InBlock.gif        
if(x>y)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            cout 
<< "Error!" << endl;
InBlock.gif            
return -1;
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

InBlock.gif    cout 
<< n << "=" << x << "+" << y << endl;
InBlock.gif    
return 0;
ExpandedBlockEnd.gif}

None.gif
None.gif
int main()
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
int n=100;
InBlock.gif    
for(;n<=1000;n+=2)
InBlock.gif        Operation(n);
InBlock.gif    
return 0;
ExpandedBlockEnd.gif}
 

转载于:https://www.cnblogs.com/Derek_nr/archive/2008/09/29/1301879.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值