THE PUZZLET PAGE

PUZZLET 036 - THE SOLUTION

' Puzzlet #036
' Find 3 consecutive primes, all less than 1000,
' whose sum is a perfect cube.
' By Dave Ellis.


declare IsPrime(p: int)
declare IsCube (c: int)
declare NextPrime()
declare PrintResult()
def i, count, prime, sum: int
def primeArray[4]: int
openconsole
print
"Searching ...": print
primeArray = 0, 2, 3, 5: ' pre-load first 3 primes
count = 1

do
    count = count + 1: 'counts primes
    sum = 0: 'initialise
    ' find sum of current 3 primes
    for i = 1 to 3
        sum = sum + primeArray[i]
    next i
    ' is the sum a perfect cube?
    if IsCube(sum)
        PrintResult()
    endif
    ' discard lowest prime, get a new highest one
    primeArray[1] = primeArray[2]
    primeArray[2] = primeArray[3]
    primeArray[3] = NextPrime()
until primeArray[3] > 1000

print: print "No more!"
print: print "Press a key to exit ..."   
do: until inkey$ <> ""
closeconsole
end

sub
IsPrime(p)
' is p a prime?
def factor, flag, root: int
root = sqrt(p): ' limits test range
factor = 3: 'first factor to test
flag = 1
do
    if
p % factor = 0
        flag = 0
    else
        factor = factor + 2
    endif
until
flag = 0 | factor > root
return flag

sub IsCube(c)
' if c is a perfect cube, returns
' 1, else returns 0

def possCube: float
possCube = exp(log(c)/3)
if possCube = int(possCube)
    return 1
else
    return
0
endif

sub
NextPrime
' get the next higher prime
' and returns it

def flag, try: int
try = primeArray[3] + 2
flag = 0
do
    if
IsPrime(try)
        flag = 1
    else
        try = try + 2
    endif
until
flag
return try


sub PrintResult
' pretty printer
def n: int
for n = 1 to 3
    print "prime #",
    print ltrim$(str$(count + n - 1)), ": ",
    print primeArray[n]
next
print "Sum: ", sum
print "Cube Root: ",
print exp(log(sum)/3)
return


PROGRAM NOTES

The main technique employed by this program is to put the lowest three consecutive primes it can find into an array,  primeArray[]. These are added together and their total stored in variable sum.  If sum turns out to be a cube, as tested by the function IsCube(), we have a solution.  

If not, the second second lowest prime overwrites the lowest in primeArray[], the highest overwrites the second lowest, and a new prime, obtained by function NextPrime(), overwrites the highest. The new one is, of course, the next highest above the old highest prime. The whole process is now repeated on primeArray[] again until eventually a solution is found.

When you run the code,  it will produce the inset screen.

This is the only solution.

Searching ...

prime #86: 439
prime #87: 443
prime #88: 449
Sum: 1331
Cube Root:  11.00

No more!

Press a key to exit ...

          

          


MAIN MENU
DOWNLOAD CODE
ARCHIVES

Site design/maintenance: Dave Ellis E-mail me!
Last Updated: February 22nd, 2004.