0

I have written the following code to check if a number is prime. I know that there are other, maybe better ways of doing i, but I just want to know what is wrong with this method. It is correctly identifying whether the number is prime or not, but in case i is prime, it is giving a segmentation error.

The code:

#include<stdio.h>
void prime(int);
int main()
{
    int a;
    printf("Enter number\n");
    scanf("%d",&a);
    prime(a);
    return 0;
}

void prime(int a)
{
    static int k=2;
    if((a%k==0)&&(a!=k))
        printf("Not a prime\n");
    else
    {
        k++;                   
        if(a==k)
            printf("Prime\n");     
        prime(a);
    }
}

Note: On trying to revise the code, I found that it makes no difference if you use a==k or k==a-1 in the else condition.

4

4 回答 4

7

首先,你的递归永远不会停止。

其次,static国家是一个非常糟糕的主意。它使代码难以测试并且不是线程安全的。更糟糕的是,如果你prime()第二次调用,它仍然会保持第一次调用的状态。

最后,这里完全不需要递归,可以简单地将其转换为迭代。

于 2013-04-01T14:40:47.307 回答
6

无限递归 -> 堆栈溢出。

于 2013-04-01T14:39:23.973 回答
3

在主要情况下,您的代码永远不会退出。你需要:

if (a==k)
    printf("Prime\n");     
else
    prime(a);
于 2013-04-01T14:40:49.057 回答
0
    if(a==k)
        printf("Prime\n"); /* Q: What happens after you find it to be prime? */
    prime(a);              /* A: You test it for primeness again..? */

我想你的意思是:

    if(a==k)
        printf("Prime\n");
    else
        prime(a);
于 2013-04-01T14:44:57.767 回答