且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C程序查找素数

更新时间:2023-02-26 17:56:48

不仅5的倍数(例如,您的代码还将9视为素数)

Not only multiples of 5 (for example, 9 is also considered prime by your code)

您的代码有缺陷.您正在使用循环,但仅检查第一次迭代,因为循环内条件的每个分支内都有一个return:

Your code is flawed. You are using a loop but only checking the first iteration, since you have a return inside each branch of the condition inside your loop:

for(i=2;i<=a/2;i++)
{
    if(a % i == 0)
    {  
        return 0;    // <------- (this one is fine, since finding a divisor means outright that this number isn't a prime)
        break;       //  also, a break after a return is redundant
    }
    else
    {
        return 1;    // <------- (however, this one is flawed)
    }
}

在这种形式下,您的代码仅执行return !(input % 2),这不是一个很好的素数查找算法:-)

In this form, your code only does return !(input % 2) which is not a very good prime finding algorithm :-)

您需要做的是检查所有迭代,并且只有当所有迭代都转到else分支时,数字才是素数.

What you need to do is check all the iteration, and only if all of them go to the else branch, the number is prime.

因此,更改为:

int primeornot(int a)
{
int i;

for(i=2;i<=a/2;i++)
{
    if(a % i == 0)
    {
        return 0;
    }
    else
    {
        continue;
    }
}
return 1; // loop has ended with no divisors --> prime!!
}

或者,更好的是:

int primeornot(int a)
{
int i;

for(i=2;i<=a/2;i++)
{
    if(a % i == 0)
    {
        return 0;
    }
}
return 1; // loop has ended with no divisors --> prime!!
}