POJ2262-Goldbach's Conjecture

Source: Internet
Author: User

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;}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.