zoukankan      html  css  js  c++  java
  • 孪生素数

     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 }
  • 相关阅读:
    Jessica's Reading Problem POJ
    FatMouse and Cheese HDU
    How many ways HDU
    Humble Numbers HDU
    Doing Homework again
    Stacks of Flapjacks UVA
    Party Games UVA
    24. 两两交换链表中的节点
    面试题 03.04. 化栈为队
    999. 可以被一步捕获的棋子数
  • 原文地址:https://www.cnblogs.com/yeshadow937/p/3884357.html
Copyright © 2011-2022 走看看