题意:给你一个数,认为它能拆成两个素数之和的形式,能,则输出x = a + b ,不能则输出 "Goldbach‘s conjecture is wrong."
思路:打印素数表,x-prime[a]检查是否为素数
代码:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 using namespace std; 5 6 #define MAXN 1000001 7 #define ll 8 int cnt; 9 long long num; 10 bool isprime[MAXN]; 11 long long prime[MAXN]; 12 13 bool datecin() 14 { 15 if(scanf("%lld",&num)!=EOF) 16 { 17 if(num==0) 18 return false; 19 return true; 20 } 21 return false; 22 } 23 24 void getprime() 25 { 26 int i,j; 27 memset(isprime,1,sizeof(isprime)); 28 isprime[0]=isprime[1]=0,cnt=0; 29 for(i=2;i*i<MAXN;i++) 30 { 31 if(isprime[i]) 32 { 33 for(j=i*i;j<MAXN;j+=i) 34 { 35 if(isprime[j]) 36 { 37 isprime[j]=false; 38 } 39 } 40 41 } 42 } 43 for(i=2;i<MAXN;i++) 44 { 45 if(isprime[i]) 46 prime[cnt++]=i; 47 } 48 } 49 50 void showisp() 51 { 52 for(int i=0;i<MAXN;i++) 53 { 54 if(isprime[i]) 55 cout<<i<<‘ ‘; 56 } 57 cout<<endl; 58 for(int i=0;i<cnt;i++) 59 { 60 cout<<prime[i]<<‘ ‘; 61 } 62 } 63 64 void datecal() 65 { 66 for(int i=0;i<cnt;i++) 67 { 68 if(num<prime[i]) 69 break; 70 if(isprime[num-prime[i]]) 71 { 72 cout<<num<<" = "<<prime[i]<<" + "<<num-prime[i]<<endl; 73 return; 74 } 75 } 76 cout<<"Goldbach‘s conjecture is wrong."<<endl; 77 } 78 int main() 79 { 80 getprime(); 81 //showisp(); 82 #ifdef ll 83 while(datecin()) 84 { 85 datecal(); 86 } 87 #endif // ll 88 return 0; 89 }
UVA, 543 Goldbach's Conjecture
时间: 2024-10-10 21:27:38