C++版浙大PAT乙級1007(20分)
阿新 • • 發佈:2021-02-03
技術標籤:PAT
https://pintia.cn/problem-sets/994805260223102976/problems/994805317546655744
這題的意思是,輸入一個正整數n,對於不超過n的質數中,有多少個相差為2的質數對。
#include<iostream> #include<math.h> using namespace std; // 判斷質數 bool isPrime(int num){ for(int n=2; n<=sqrt(num); n++){ if(num % n == 0){ return false; } } return true; } int main(){ int a, count = 0; cin >> a; if(a < 5){ cout << 0; return 0; } for(int odd=3, pre=3; odd<=a; odd+=2){ if(isPrime(odd)){ if(odd-pre==2) count ++; pre = odd; } } cout << count; return 0; }