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.
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.
Code
#include<iostream>#include<math.h>usingnamespace std;intmain(){
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;}