简体   繁体   中英

recursively check if number is a prime

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.

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

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

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 .

#include<iostream>
using namespace std;
bool findPrime(int x,int y);
int main()
{int n;
cout<<"enter the number to be checked \n";
cin>>n;
  int x=findPrime(n,n-1);
  if(x==1)
    cout<<"its a prime number";
  else
    cout<<"its not prime";
}
bool findPrime(int x,int y)
{
    if(x%y==0&&y!=1)
    {
        return false;
        }
    else{
        if(y==1)
        return true;
    else
        return findPrime(x,y-1);
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM