CF1269A Equation

题意

要找两个合数,使他们两个的差为(n)(n)为题目给出的数

思路

我们可以枚举减数(now),判断一下是不是质数,如果是质数就让(now++),然后用一个数(tot)记录被减数,也就是(now)(n),判断(tot)是不是质数,如果是质数再让(now++),如果不是质数我们就找到了答案,因为我们已经保证了(now)为合数,所以就可以直接跳出循环输出答案啦~

因为数据范围并不大,所以我们可以直接判断一个数是不是质数,如下

//判断是否为质数,是质数返回1,否则返回0 
bool check(int wh) {
	if(wh <= 1) return 0; 
    if(wh == 2) return 1;
	for(int i = 2; i * i <= wh; i++) if(wh % i == 0) return 0;
	return 1;
}

代码

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

const int A = 5e5 + 11;
const int B = 1e6 + 11;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;

inline int read() {
	char c = getchar(); int x = 0, f = 1;
	for( ; !isdigit(c); c = getchar()) if(c == '-') f = -1;
	for( ; isdigit(c); c = getchar()) x = x * 10 + (c ^ 48);
	return x * f;
}

//判断是否为质数,是质数返回1,否则返回0 
bool check(int wh) {
	if(wh <= 1) return 0; if(wh == 2) return 1;
	for(int i = 2; i * i <= wh; i++) if(wh % i == 0) return 0;
	return 1;
}

int main() {
	int n = read(), now = 2, tot;
	while(1) {
		if(check(now)) now++; 
        //判断now是否为质数,如果是质数就++,否则继续判断tot的值
		else {
			tot = now + n;
			if(check(tot)) now++;
            //判断tot是否为质数,如果不是质数就可以跳出输出答案了
			else break;
		}
	}
	return cout << tot << " " << now << '
', 0;
}
原文地址:https://www.cnblogs.com/loceaner/p/12080330.html