RosettaCodeData/Task/Strong-and-weak-primes/FreeBASIC/strong-and-weak-primes.basic
2023-07-01 13:44:08 -04:00

60 lines
1.6 KiB
Text

#include "isprime.bas"
function nextprime( n as uinteger ) as uinteger
'finds the next prime after n, excluding n if it happens to be prime itself
if n = 0 then return 2
if n < 3 then return n + 1
dim as integer q = n + 2
while not isprime(q)
q+=2
wend
return q
end function
function lastprime( n as uinteger ) as uinteger
'finds the last prime before n, excluding n if it happens to be prime itself
if n = 2 then return 0 'zero isn't prime, but it is a good sentinel value :)
if n = 3 then return 2
dim as integer q = n - 2
while not isprime(q)
q-=2
wend
return q
end function
function isstrong( p as integer ) as boolean
if nextprime(p) + lastprime(p) >= 2*p then return false else return true
end function
function isweak( p as integer ) as boolean
if nextprime(p) + lastprime(p) <= 2*p then return false else return true
end function
print "The first 36 strong primes are: "
dim as uinteger c, p=3
while p < 10000000
if isprime(p) andalso isstrong(p) then
c += 1
if c <= 36 then print p;" ";
if c=37 then print
end if
if p = 1000001 then print "There are ";c;" strong primes below one million"
p+=2
wend
print "There are ";c;" strong primes below ten million"
print
print "The first 37 weak primes are: "
p=3 : c=0
while p < 10000000
if isprime(p) andalso isweak(p) then
c += 1
if c <= 37 then print p;" ";
if c=38 then print
end if
if p = 1000001 then print "There are ";c;" weak primes below one million"
p+=2
wend
print "There are ";c;" weak primes below ten million"
print