孪生素数

 

 1 #include<iostream>
 2 #include<time.h> 
 3 #include<math.h>
 4 #include<assert.h>    //使用 assert.h 中的 assert 宏来限制非法函数的调用; 
 5 using namespace std;
 6 
 7 //  判断是否为素数 
 8 int is_prime(int x)        //尽量把谓词(用来判断某事物是否具有某特性的函数) 命名成 is_XXX 的形式,返回int型的值,非0表示真,0表示假; 
 9 {
10     assert(x>=0);           //当 x>=0 不成立时,程序将异常终止,并给出提示信息; 
11     if(x==1)    return 0;    
12     int m = floor(sqrt(x)+0.5);      //四舍五入避免浮点误差 ,求sqrt(x)的原因是:如果一个数在 0~sqrt(x) 不能被整除,那么它在 0~x 也一定不能被整除; 
13     for(int i=2;i<=m;i++)
14     {
15         if(x%i==0)        //如果x有其他因子,可断定x不是素数; 
16             return 0;
17     } 
18     return 1;
19 }
20 
21 int main()
22 {
23     clock_t start,end;  //计时定义 
24     int i,m;
25     cin>>m;
26     start = clock();
27     for(i=m-2;i>=3;i--)
28     {
29         if(is_prime(i) && is_prime(i+2))
30         {
31             cout<<i<<' '<<i+2<<endl;
32             break;
33         }
34     }
35     end = clock();
36     cout<<"time used = "<<(double)(end-start)/CLOCKS_PER_SEC<<endl;
37     return 0;
38     
39 }

 

转载于:https://www.cnblogs.com/yeshadow937/p/3884357.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值