April 23, 2024, 12:55:33 PM

News:

IonicWind Snippit Manager 2.xx Released!  Install it on a memory stick and take it with you!  With or without IWBasic!


Puzzlet #36

Started by GWS, August 04, 2015, 09:21:01 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

GWS

For puzzle fans, here's another of Dave Ellis's puzzles from many moons ago ..  ;D

This one is a Prime Number puzzle - to find 3 consecutive primes, all less than 1000,
whose sum is a perfect cube.


' 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)

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 "Done!"
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)
' is c a perfect cube?
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
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 n
print 
print "Sum: ", sum
print "Cube Root: ",
print exp(log(sum)/3)
return



Hope you find it interesting ..

Best wishes, :)

Graham




Tomorrow may be too late ..