[Solved] check if number is prime using recursion with only one parameter in c language [closed]


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

solved check if number is prime using recursion with only one parameter in c language [closed]