I've got a task in my lesson to write a function that will check if a number is prime, it will return 1 if it is and 0 if it is not and all of that to do recursively. the function will look like that :int isPrime(int num); I've tried everything and searched everywhere and came to the conclusion that it's possible only with static int which I did not learn yet so can't use it or with two parameters. does anyone know if there is a way to solve it with only one parameter ad no static int? thanks.
2 Answers
This was a trick question: you are supposed to use recursion, but unless you are barred from using loops, a classic solution with a for loop can be made to comply with the recursion requirement.
Here is a function isPrime that has a single argument and uses a classic loop and recursion to test prime divisors:
int isPrime(int n) {
if (n <= 1)
return 0;
if (n % 2 == 0)
return n == 2;
for (int p = 3; p * p <= n; p += 2) {
if (isPrime(p) && n % p == 0)
return 0;
}
return 1;
}
The above code only performs the modulo operation for prime divisors. It is a false optimisation because it is actually more costly to determine if p is prime with a recursive call than to compute n % p.
4 Comments
So here is my solution to this questionable assignment. It contains only functions taking one int argument and uses recursion and no loop:
#include <iostream>
#include <functional>
std::function<bool(int)> isPrime(int x) {
return [x](int p) {
if (x <= 2) return true;
return (p % (x - 1) != 0) && (isPrime(x - 1)(p));
};
}
int main() {
if (isPrime(19)(19)) std::cout << "is prime" << std::endl;
}
static int IsPrime(int n) { if (n < 2) return 0; for (int d = 2; d*d <= n; ++d) if (n % d == 0) return 0; /* Look, recursion! */ return !IsPrime(1); }stdbool.hand usebool isPrime(int num)and returntrueorfalse