小红的合数寻找
A-小红的合数寻找_牛客周赛 Round 79
题目描述
小红拿到了一个正整数 x,她希望你在 [x,2×x] 区间内找到一个合数,你能帮帮她吗?
一个数为合数,当且仅当这个数是大于1的整数,并且不是质数。
输入描述
在一行上输入一个正整数 x (1 ≤ x ≤ 100)。
输出描述
如果范围内不存在符合条件的合数,则输出 -1。否则,输出一个正整数代表答案。
如果存在多个解决方案,您可以输出任意一个,系统会自动判定是否正确。注意,自测运行功能可能因此返回错误结果,请自行检查答案正确性。
示例1
------
输入
----
1
输出
----
-1
说明
----
在这个样例中,我们需要在 [1,2] 区间内找到一个合数。根据定义,1 不是合数,2 是质数,所以范围内不存在合数。
示例2
------
输入
----
5
输出
----
8
说明
----
在这个样例中,我们需要在 [5,10] 区间内找到一个合数。根据定义,6,8,10 均是合数,所以输出任意一个均为正确答案。
思路:
模拟就完事了
代码如下:
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 1e5+10;
int arr[N];
bool found;
bool isnt_prime(int x)
{
if(x < 2)
return false;
if(x == 2)
return false;
for(int i = 2 ; i < x ; i++)
{
if(x % i == 0)
return true;
}
return false;
}
bool check(int x)
{
if(isnt_prime(x))
{
return true;
}
else
{
return false;
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n,ans = 0;
cin >> n;
for(int i = n ; i <= 2*n ; i++)
{
if(check(i))
{
found = true;
ans = i;
break;
}
}
if(found)
cout << ans;
else
cout << -1;
return 0;
}