Reprinted please indicate the source: Thank you http://user.qzone.qq.com/289065406/blog/1299063931
Tip: W is really a big BT .... I used optimization or barely got rid of the AC. A person I met, with 16 Ms AC, orz ....
Solution:
If we still calculate all the prime numbers in 1 million using the conventional method (I .e. division modulo), the time complexity is incredible. Therefore, it is necessary to convert the idea for optimization, replace division with addition, and exchange space for time! The calculation addition is definitely much faster than division, and there are 1 million addresses, that is, about 1 MB of memory. I believe that 99% of computers can still be easily used out now!
Optimize the determination of prime numbers:
1. The prime number is an even number except 2, first halved
2. recursion: If a number cannot be divisible by all prime numbers smaller than it, it is a prime number.
3. root code: If a number x cannot be divisible by all numbers in [2, root number x], it is a prime number.
Combining the above three methods can greatly reduce the time complexity. In fact, the 3rd point is the most effective method to save time and reduce the division.
//Memory Time //228K 907MS #include<iostream>using namespace std;bool judge_prime(int digit){int i,flag;if(digit%2==0)return false;else{for(i=3,flag=1;i*i<=digit;i+=2)if(digit%i==0){flag=0;break;}if(flag)return true;}return false;}int main(void){int temp,num,flag;for(;;){cin>>num;if(num%2!=0||num<6)return 0;for(temp=3,flag=1;temp<=num/2;temp+=2)if(judge_prime(temp)&&judge_prime(num-temp)){cout<<num<<" = "<<temp<<" + "<<num-temp<<endl;flag=0;break;}if(flag)cout<<"Goldbach's conjecture is wrong."<<endl;}return 0;}