First of all I know this is kind of a simple question and I am a beginner so please bear with me .
I have been having problems with this exercise in Java and I'm practising for a test and this one really messed up my self-confidence.
So anyways the problem looks like this
// Returns true if (and only if) n is a prime number; n > 1 is assumed.
private static boolean isPrime(long n) {
return isPrime(n, 2);
// See the method isPrime below.
}
// Helper method for isPrime ...
private static boolean isPrime(long n, long m) {
return (m * n > (m /* TODO: modify expression if necessary */))
|| (n % m == (0 /* TODO: modify expression if necessary */)
&& isPrime((m /* TODO: modify expression if necessary */), n + 1));
}
So you're supposed to fill these expressions inside of the brackets where TODO is .
My problem is that I just can't trace what this does.
isPrime((.....),n+1);
If someone could just offer some advice on how to start solving this problem I would be very grateful .
解决方案
This problem is not amenable to recursive solution. Or at least not an efficient recursive solution.
The definition of primality is that N is prime if it is not divisible by any positive integer other than itself or 1. The normal way to handle that using recursion would be to define a recursive "is_divisible" function:
# for integers m >= 1
is_prime(m):
return is_divisible(m, 1)
is_divisible(m, n):
if n >= m: return true
if n == 1: return is_divisible(m, n + 1)
if m % n == 0: return false // HERE
return is_divisible(m, n + 1)
OR (more efficient 3 parameter version)
# for all integers m
is_prime(m):
if m == 1: return false
if m >= 2: return is_divisible(m, sqrt(m), 2)
error "m is not a positive integer"
is_divisible(m, max, n) :
if n >= max: return true
if m % n == 0: return false // HERE
return is_divisible(m, max, n + 1)
(In the literature, they often call functions like is_divisible "auxiliary" functions. This is a common tool in functional programming.)
If you try to "optimize" that to only consider prime numbers at HERE, you will end up with double recursion .. and exponential complexity.
This is all very "unnatural" in Java, and will be horribly inefficient (even compared with a naive primality test using a loop1) because Java doesn't do tail-call optimization of recursion. Indeed, for large enough N you will get a StackOverflowError.
1 - A better, but still simple approach is the Sieve of Erathones. There are better tests for primality than that, though they are rather complicated, and in some cases probabilistic.