一本通-1403:素数对(函数)¶
【题目描述】 两个相差为2的素数称为素数对,如5和7,17和19等,本题目要求找出所有两个数均不大于n的素数对。
【输入】 一个正整数n(1≤n≤10000)。
【输出】 所有小于等于n的素数对。每对素数对输出一行,中间用单个空格隔开。若没有找到任何素数对,输出empty。
【输入样例】 100
【输出样例】 3 5 5 7 11 13 17 19 29 31 41 43 59 61 71 73
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
#include <cmath>
#include <climits>
#include <cstdio>
using namespace std;
bool isPrime(int n)
{
if (n <= 1) return false;
if (n == 2) return true;
if (!(n & 1)) return false;
int limit = sqrt(n) + 1;
for (int i = 3; i <= limit; i += 2) {
if (n % i == 0) return false;
}
return true;
}
int main()
{
std::ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n;
cin >> n;
if (n >= 5) {
for (int i = 3; i <= n; i += 2) {
if (isPrime(i)) {
if (i + 2 <= n && isPrime(i + 2))
cout << i << " " << (i + 2) << endl;
}
}
}
return 0;
}