PAT-1007 prime number pair conjecture main ideas, codes and comments

1007 素数对猜想 (20)
让我们定义d
​n
​​ 为:d
​n
​​ =p
​n+1
​​ −p
​n
​​ ,其中p
​i
​​ 是第i个素数。显然有d1
​​ =1,且对于n>1有d
​n
​​ 是偶数。“素数对猜想”认为“存在无穷多对相邻且差为2的素数”。

现给定任意正整数N(<105
​​ ),请计算不超过N的满足猜想的素数对的个数。

输入格式:
输入在一行给出正整数N。

输出格式:
在一行中输出不超过N的满足猜想的素数对的个数。

输入样例:
20
输出样例:
4
  1. The meaning of the question:
    Given a number n,
    find the prime numbers within n.
    Determine the number of adjacent prime number pairs with a difference of 2 among these prime numbers.
  2. Idea
    First, determine which prime numbers are within n. If
    a prime number is divided by its square root, every number cannot be divided.
    Second, determine whether the difference between adjacent prime numbers is 2.
  3. Code
#include<iostream>
#include<math.h>
using namespace std;
int main(){
    
    
	int n,i,j;
	int k=0;	//新数组 
	int count=0;	//满足条件个数 
	cin>>n;
	int str[100001];
	//判断素数 对于m,从2到sqrt(m),如果m模除能除,则不是素数,否则为素数,此时>sqrt(i) 
	for(i=2;i<=n;i++){
    
    
		for(j=2;j<=sqrt(i);j++){
    
    
			if(i%j==0)
				break;
		}
			if(j>sqrt(i))
				str[k++]=i;
		}
	//相邻且差为2 
	for(i=0;i<k;i++){
    
    
		if(str[i]+2==str[i+1])
			count++;
	} 
	cout<<count<<endl;
}

Guess you like

Origin blog.csdn.net/weixin_44549439/article/details/112788142