Saturday, February 7, 2009

Summation of Four Primes

Here's a different algorithm for our current project, Summation of Four Primes.

If you could write a next_lowest_prime(n) method, you might use it to find n's next lowest prime (if n is prime, return n).

Then you could do it again, this time calling the method with next_lowest_prime(n - [the "previous" next lowest prime]). If you do that 4 times, you'll get 4 primes that add up to your n. But say n = 20.

next_lowest_prime(20) = 19. So, 19 is one.
n' = 20 - 19 = 1. Obviously we have a problem. But there is a simple solution to fix this. Declare a variable, r = 6.

Why 6?

We'll always be able to obtain the first prime, but in cases such as the one above, the next lowest prime is one (or zero, two, or three...) below n. So we must have a way to guarantee that there are 3 spaces for the minimum prime, 2. So 2x3=6.

Then:
four_primes[i] = next_lowest_prime(n' - r)
n' = n - four_primes[i]
r -= 2
guarantees you will obtain a prime that leaves enough room for the rest of the 4 primes. Run the algorithm for n = 20, again.

N.L.P(20 - 6) = 13
N.L.P(7 - 4) = 3
N.L.P(4 - 2) = 2
N.L.P(2 - 0) = 2

No comments:

Post a Comment