1007. Prime Pair Conjecture (20)
Let us define d n as: d n = p n+1 - p n , where p i is the ith prime number. Clearly there is d 1 =1 and d n is even for n>1. The "prime pair conjecture" states that "there are infinitely many pairs of adjacent prime numbers that differ by 2".
Now given any positive integer N (< 10 5 ), count the number of pairs of prime numbers not exceeding N that satisfy the conjecture.
Input format: Each test input contains 1 test case, giving a positive integer N.
Output format: The output of each test case occupies one line, and does not exceed the number of prime pairs of N satisfying the conjecture.
Input sample:20Sample output:
4
About the prime number judgment function:
Type 1: Judging according to the definition, when N (<10 5 ) is large, this kind of function has a very large amount of calculation, and displays "operation timeout" after submitting the program:
1 bool prime(int num){ 2 int i; 3 if(num==1) return false; 4 for(i=2;i<num;i++) 5 if(num%i==0) return false; 6 return true; 7 }
Type 2: Judging within the range of the square root of N, which greatly reduces the amount of computation, so use this function:
1 bool prime(int num){ 2 int i,k; 3 if(num==1) return false; 4 k=int(sqrt(num)); 5 for(i=2;i<=k;i++) 6 if(num%i==0) return false; 7 return true; 8 }
programming:
method one:
1. Find all prime numbers within the range of N and store them in the array prime_num[]. Since there are a total of 9592 prime numbers within the range of 10 5 , the number of array elements should not be less than 9592
2. Compare the elements in the prime_num[] array to find the number of the last digit that is 2 larger than the previous digit
The C++ code is as follows:
1 #include <bits/stdc++.h> 2 using namespace std; 3 bool prime(int num){ 4 int i,k; 5 if(num==1) return false; 6 k=int(sqrt(num)); 7 for(i=2;i<=k;i++) 8 if(num%i==0) return false; 9 return true; 10 } 11 int main() { 12 int prime_num[9600]; 13 int i,j=0,count=0; 14 long n; 15 cin>>n; 16 for(i=2;i<=n;i++){ 17 if(prime(i)){ 18 prime_num[j]=i; 19 j++; 20 } 21 else continue; 22 } 23 for(i=0;i<j-1;i++) 24 if(prime_num[i+1]-prime_num[i]==2) ++count; 25 cout<<count; 26 system("pause"); 27 return 0; 28 }
Method Two:
When N>2, all prime numbers are odd, so only the number of adjacent odd numbers that are all primes is required.
The C++ code is as follows:
1 #include <bits/stdc++.h> 2 using namespace std; 3 bool prime(int num){ 4 int i,k; 5 if(num==1) return false; 6 k=int(sqrt(num)); 7 for(i=2;i<=k;i++) 8 if(num%i==0) return false; 9 return true; 10 } 11 int main() { 12 int i,count=0; 13 long n; 14 cin>>n; 15 for(i=3;i+2<=n;i+=2){ 16 if(prime(i)) 17 if(prime(i+2)) count++; 18 else continue; 19 } 20 cout<<count; 21 system("pause"); 22 return 0; 23 }