Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

recursively check if number is a prime

Tags:

c++

recursion

I'm trying to check whether the number is a prime(by dividing it by all numbers below n). Here's my attempt :

bool isPrime(int n, int d){
    if (d == 1)
        return true;
    else{
        if (n % d == 0){
            return false;
        }
        else
            return (n,d-1);
    }
}

n - the number to check whether it is prime. d - number below n, when calling the function n-1.

Please help me figure out what am I doing wrong.

like image 898
Marijus Avatar asked Mar 27 '11 17:03

Marijus


3 Answers

You aren't recursively calling your function. return (n,d-1); should be return isPrime(n,d-1);

like image 177
GWW Avatar answered Oct 21 '22 02:10

GWW


Please don't write this in such a way! For more or less normal input, recursive approach will eat all the stack up! Just go for the old good iterative way.

Of course, the brute force solution is not the fastest one. You could try Eratosthenes' sieve, or some of numerous more advanced tests.

like image 37
Vlad Avatar answered Oct 21 '22 02:10

Vlad


You just need to include condition for checking 1 if it is prime or not.

bool isPrime(int n, int d)
{
    if(n<2)
        return 0;
    if(d == 1)
        return true;
    else 
    {
        if(n % d == 0) 
            return false;
        else
            return isPrime(n, d - 1);
    }
}
like image 41
Shubham Godara Avatar answered Oct 21 '22 03:10

Shubham Godara