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);
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With