性感素数 题解C++

#include <iostream>
#include<cmath>

using namespace std;

bool isvegetable(int tar)
{
    if (tar<=1) return false;
    int i = 2;
    while (i <= sqrt(tar))
    {
        if (tar % i == 0)
        {
            return false;
        }
        i++;
    }
    return true;
}

int main()
{
    int tar; cin >> tar;
    if (isvegetable(tar) && isvegetable(tar - 6))
        cout << "Yes\n" << tar - 6 << endl;
    else if (isvegetable(tar) && isvegetable(tar + 6))
        cout << "Yes\n" << tar + 6 << endl;
    else
    {
        cout << "No\n";
        while (!(isvegetable(tar)&&(isvegetable(tar-6)||isvegetable(tar+6))))tar++;
        cout << tar << endl;
    }


}

代码奉上。

素数定义:

质数 (素数)只能被 1 或自己整除。

同时它必须是大于 1 的整数。

其中,判断素数时使用暴力枚举,所有小于根号下目标数的正整数中,是否有数能够被整除。如下:

bool isvegetable(int tar)
{
    if (tar<=1) return false;
    int i = 2;
    while (i <= sqrt(tar))
    {
        if (tar % i == 0)
        {
            return false;
        }
        i++;
    }
    return true;
}

猜你喜欢

转载自blog.csdn.net/weixin_61720360/article/details/125647461