PAT Level B 1007. Prime number pair conjecture (20 points)

Title description:
Let us define d​n​​ as: d​n=p​n+1−p​n, where p​i is the i-th prime number. Obviously d
​1
​​ =1, and d
​n
​​ is even for n>1 . The "prime pair conjecture" believes that "there are infinitely many pairs of adjacent prime numbers with a difference of 2".

Now given any positive integer N (<10
​5
​​ ), please count the number of prime number pairs that do not exceed N that satisfy the conjecture.

Input format:
Input a positive integer N in one line.

Output format:
output the number of prime number pairs that do not exceed N and satisfy the conjecture in one line.

Input sample:
20
Output sample:
4

Problem-solving idea: This
problem is stuck in the
original idea because of the running timeout . First write a function to judge whether it is a prime number, then install these prime numbers in a vector, and then calculate whether there is a difference between two adjacent numbers 2; The result has timed out.
Big idea:
The function isprime for determining prime numbers is written like this: For the number a, i from 2 to the radical a, if a is divisible by one of i, it means that i is not a prime number, return false, otherwise it means that a is a prime number return true; Input the data N, the i in the for loop judges whether i-2 and i are prime numbers in turn from 5 to N. If they are all prime numbers, count the number of cnt++, and finally output cnt.
This is the difference of 2 adjacent It’s easy to judge whether it is a prime number by number, and it is also relatively simple to use a function to judge prime number.
Problem-solving code:

#include<iostream>
using namespace std;
bool isprime (int a){
    
    //自定义一个函数判断是否为素数 
	for(int i=2;i*i<=a;i++){
    
    
		if(a%i==0){
    
    
			return false;
		}
	}
	return true;
}
int main() {
    
    
	int n;
	int sum=0;
	cin>>n;
	for(int i=5; i<=n; i++) {
    
    
	  if(isprime(i-2)&&isprime(i)){
    
    
	  	sum++;
	  }
 
	}
	cout<<sum;
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_44867340/article/details/107941110