开发者

explain this prime number program [C]

#include<stdio.h>

main()
{
    int n;

    int a,b,flag=1;
    scanf("%d",&n);

    for(a=2; a<=n; a++)
    {
        if(n % a == 0)
        {
            printf("not prime");
            flag = 0;
            break;
        }
    }

    if(flag == 1)
    {
        p开发者_如何学JAVArintf("is prime");
    }

    getch();
}

when you use this for loop

for(a=2; a<=n; a++)

when user will input 2 it will print "not prime:

if you put that if(flag == 1) statement inside the for loop it doesn't print anything when the user inputs 2. Why is that if(flag == 1) outside that for loop

#include<stdio.h>
main()
{
    int i, num, flag = 1;
    scanf("%d",&num);
    for(i=2; i<=sqrt(num); i++)
    {
        if(num%i==0)
        {
            printf("not prime");
            flag=0;
            break;
        }
    }

    if(flag==1)
    {
        printf("is prime");
    }

    getch();
}

when you will use square root in for loop

for(i=2; i<=sqrt(num); i++)

then it give correct result if you enter 2 then it prints 2 is prime number WHY ?

and what is flag variable how does it work ?


The problem is that this line is wrong:

for(a=2; a<=n; a++)

It should be this:

for(a=2; a<n; a++)

Because n is always divisible by itself it will mean that n % a == 0 when a is n. This does not mean the number is not prime. A prime is exactly divisible by 1 and itself, but no other integer.

When you change the test to a <= sqrt(num) you also happen to fix this bug.


for(a=2; a <= n; a++)

should be

for(a=2; a < n; a++)
         //^ difference

Also, when you use sqrt(n), you better write this outside the loop to improve performance:

int m = sqrt(n); //store the result in int type
for(a=2; a <= m ; a++)

In this way, you calculate sqrt(n) just ONCE, instead of in every iteration, and instead of relying on the compiler to optimize this step.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜