要在 C++ 中找到素数,我会得到像 9 和 15 这样的数字也是素数。请找出代码中的错误

to find number to be prime in c++ I'm getting numbers like 9 and 15 also prime . pls find the error in the code

通过使用此代码,我得到了 9 和 15 这样的数字也是质数。请在代码中找到错误,如果可能请编辑我的代码以查找错误 这是代码--

`#include<iostream>
    using namespace std;
    int main()
    {
        int n;
        cout<<"Enter the number : ";
        cin>>n;
        int flag=0;
        //to check prime check from 2 to n
        for(int i=2;i<=n;i++)
        {
            if(n%2==0)
            {
                cout<<n<<" is a non-prime number";
                flag++;
                break;
            }
            else
            {
                if(flag==0)
                {
                    cout<<n<<" is a prime number";
                    break;
                }
            }
        }
        return 0;
    }

您的检查逻辑有缺陷,因为您正在检查 %2,您应该检查 %i。我还添加了一些优化,因为您只需要检查到 n/2.

检查一个数是否为质数:

    #include<iostream>
    using namespace std;
    int main()
    {
        int n;
        cout<<"Enter the number : ";
        cin>>n;
        bool prime=true;
        //to check prime check from 2 to n
        for(int i=2;i<=n/2;i++)
        {
            if(n%i==0)
            {
                prime = false;
                break;
            }
        }
        if (prime)
            cout<<n<<" is a prime number";
        else
            cout<<n<<" is a non-prime number";
        return 0;
    }

您的代码不检查数字是否为素数,而只是检查从 2 到 n 的所有数字是否为偶数或奇数,并且当 i 的值变为奇数时(即 3,就在它的第一次迭代)代码执行这些行

cout<<n<<" is a prime number";
flag++;

还有什么意义

flag = 0 

如果您使用 break 来终止循环。

你一定想写这样的东西

#include<iostream>
using namespace std;
int main()
{
    int n;
    cout<<"Enter the number : ";
    cin>>n;
    int flag=0;
    for(int i=2;i<=n;i++)
    {
        if(n%i==0)
        {
            cout<<n<<" is a non-prime number";
            flag++;
            break;
        }
    }
    if(flag==0)
    {
        cout<<n<<" is a prime number";
        break;
    }
    return 0;
}

也是为了让这段代码更好写

for(int i=2;i<=sqrt(n);i++)

改为