一个数(3000内)等于两个素数之和

来源:互联网 发布:淘宝卖家收入怎么查看 编辑:程序博客网 时间:2024/06/10 11:11

 

  1. #include "stdafx.h"
  2. #include "iostream"
  3. using namespace std;
  4. unsigned int a[500]; // 用于存放前500个素数
  5. unsigned int f(unsigned int x);  
  6. bool is(unsigned int x);
  7. void init() //  初始化数组全零
  8. {
  9.     for(int i=0; i<500; i++)
  10.     {
  11.         a[i]=0;
  12.     }
  13. }
  14. void  init2()  //  用素数序列来初始化数组
  15. {
  16.     int j=0;
  17.     for(unsigned int i; i<=4294967294; i++)
  18.     {
  19.         if(is(i))
  20.         {
  21.             a[j]=i;
  22.             j++;
  23.         }
  24.         if(j>500)
  25.         {
  26.             break;
  27.         }
  28.     }
  29. }
  30. bool is(unsigned int x) //  判断一个数x是不是素数,是返回true
  31. {
  32.     unsigned int s;
  33.     if(x<2) return false;
  34.     if(x == 2 ) return true;
  35.     s = f(x);
  36.     for(unsigned int i=2 ; i<=s ; i++)
  37.     {
  38.         if(x%i==0) return false;
  39.     }
  40.     return true;
  41. }
  42. unsigned int f(unsigned int x)  //返回一个数,这个数大于他的平方根
  43. {
  44.     unsigned int i=0;
  45.     unsigned int s=1;
  46.     while(x>=s)
  47.     {
  48.         x-=s;
  49.         s+=2;
  50.         i++;
  51.     }
  52.     i++;
  53.     return  i;
  54. }
  55.     
  56. int main()
  57. {
  58.     init();
  59.     init2();
  60.     int i;
  61.     int x;
  62.     int y;
  63.     cout << a[499] << endl;  //打印数组中最大的素数
  64. loop:
  65.     cout << "input a number : " ;
  66.     cin >> i ;
  67.     if(i<=2) 
  68.     {
  69.         cout << "The number must bigger than 3";
  70.         goto loop;
  71.     }
  72.     for(x=0; x<=499; x++)
  73.     {
  74.         for(y=x+1; y<=499; y++)
  75.         {
  76.             if(a[x]+a[y]==i) goto end;
  77.         }
  78.     }
  79.     cout << "error " <<endl;
  80. end:
  81.     cout << i << "=" << a[x] << " + " <<  a[y] << endl;
  82.   
  83.     cout << endl;
  84. }

一个数(3000内)等于两个素数之和

 

原创粉丝点击