C++找出最靠近20的兩個質數!!!!(急

C++找出最靠近20的兩個質數!!!!

1 個解答

評分
  • 6 年前
    最佳解答

    17, 19, 23

    2015-01-12 10:03:15 補充:

    #include<iostream>

    using namespace std;

    bool prim(int n){

    if(2>n)return false;

    if(2==n)return true;

    if(0==(1&n))return false;

    int i;

    for(i=3;(i*i)<n&&(n%i); i+=2);

    return i*i>n;

    }

    int main(void){

    for(int n;cout<<"Enter a positive integer(0 to stop): "&&cin>>n&&n;){

    int i,m,s,c;

    for(m=-1,s=!(1&n),i=1+!s,c=0;c<6;s+=i*(m>0),m*=-1)

    if(prim(n+s*m))cout<<(++c)<<": "<<n+s*m<<endl;

    }

    return 0;

    }

    Enter a positive integer(0 to stop): 20

    1: 19

    2: 17

    3: 23

    4: 13

    5: 11

    6: 29

    Enter a positive integer(0 to stop): 10000

    1: 10007

    2: 10009

    3: 9973

    4: 9967

    5: 10037

    6: 10039

    Enter a positive integer(0 to stop): 0

還有問題?馬上發問,尋求解答。