Search code examples
c++returnuser-defined-functionsprime31

Why a return statement of my user defined function doesn't work at some case?


A prime checking function of mine shows 9,15 etc as prime where they aren't. My code is :

#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;
}

I made the code pretty much graphical so that errors can be found easily. When I input 9 my program shows like:

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.

It should print "Going to main function." once and then come to main function. But it doesn't and goes through the entire function and then comes to main function. Can anyone help me with this problem?


Solution

  • Instead of

    prime_function(num,++i);
    

    You want

    return prime_function(num,++i);