PAT Brush Questions of Grade B 1007 Prime Number Pair Conjecture

PAT Brush Questions Grade B 1007 (cpp)

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 for n>1, d ​n is even. The "prime pair conjecture" believes that "there are infinitely many pairs of adjacent prime numbers with a difference of 2".
       Now given an arbitrary positive integer N(<10 . 5 ), does not exceed Calculate Nthe number of prime numbers satisfying conjecture pair.

Input format

       Enter a positive integer on one line N.

Output format

       Output Nthe number of prime number pairs that meet the conjecture not to exceed in one line .

Input sample

20

Sample output

4

problem analysis

       The main Nidea of this question is to calculate the prime number pairs within which the difference is 2. The prime number starts from 2, that is to say, our loop also starts from 2. However, 2+2=4 is an even number, that is to say, there is no prime number pair with one side of 2, and 3+2=5. A prime number pair is (3,5). We take 3 as the boundary position of the loop traversal, for each prime number P, see if P+2 is a prime number, until the loop reaches the judgment condition is not established.
Note :
       ① Note that when enumerating, ensure that i and i+2 are both within the range of n to be considered a prime number pair.
       ② 1 is not prime


Code

The core code is as follows:

bool IsPrime(int num) {
    
      //判断是否为素数
	for (int i = 2; i <= sqrt(num); i++) {
    
    
		if (num%i == 0)
			return false;
	}
	return true;
}
int Number_of_PairPrime(int n) {
    
      //计算素数对个数
	int number = 0;  //此变量代表素数对的个数
	for (int i = n; i > 3; i--) {
    
      //从最后一位开始循环
		if (!IsPrime(i)) //如果不是素数则跳过
			continue;
		else {
    
    
			int temp = i;
				while (temp >= i - 3) {
    
     //直到temp<i-2
					if (IsPrime(temp) && i - temp == 2){
    
        //如果是temp是素数且与i差2,则个数加一
						number++;
					}
					temp--;
			    }
		}
	}
	return number;
}

The complete code is implemented as follows: the

       code is here~

Run implementation

Run implementation

Guess you like

Origin blog.csdn.net/ThunderF/article/details/90692781