0

我的素数检查功能将 9,15 等显示为素数,而它们不是。我的代码是:

#include<iostream>
#include<cstdio>
using namespace std;
int prime_function(int num, int i);
int main(){
    int num,flag=0;
    while (cin>>num){
        if(num!=1){
            flag=prime_function(num,2);
            if(flag==0)
                printf("%d isn't a prime.\n",num);
            else {
                printf("%d is a prime.\n",num);
            }   
        }
        else {
            printf("%d is a prime.\n",num);
        }
    }
    return 0;
}

int prime_function(int num, int i)
{
    if(num%i==0){
        printf("when num mod i == 0, num=%d    i=%d\n",num,i);
        return 0;//This Statement doesn't work for like num=9,15...
    }
    else if((i*i)+1<=num){
        printf("when num mod i != 0, num=%d    i=%d\n",num,i);
        prime_function(num,++i);
    }
    printf("Going to main function.\n");
    return 1;
}

我使代码非常图形化,以便可以轻松找到错误。当我输入 9 时,我的程序显示如下:

when num mod i != 0, num=9    i=2
when num mod i == 0, num=9    i=3
Going to main function.
Going to main function.
9 is a prime.

它应该打印“Going to main function”。一次然后进入主要功能。但它没有,而是遍历整个函数,然后进入主函数。谁能帮我解决这个问题?

4

2 回答 2

2

代替

prime_function(num,++i);

你要

return prime_function(num,++i);
于 2015-07-18T08:39:17.947 回答
1

您需要检查递归调用的返回值prime_function;目前,它的返回值被忽略,并且在不应该的情况下,该函数将返回 true。

else if((i*i)+1<=num){
    printf("when num mod i != 0, num=%d    i=%d\n",num,i);
    if (!prime_function(num,++i))
         return 0;
}
于 2015-07-18T08:39:46.670 回答