## Thursday, April 19, 2012

### Prime Numbers

I was watching the video below and I spotted that the Benchmark BM9 is getting Prime Numbers.

This reminded me of a program I wrote in 1986 (20 I'm old years ago) to work out Primes on an Apple ][ in school.
So, I just had to fire up a BASIC interpreter (BASIC-256) to see if I could recreate it again.
Below is the code I did today with loads of REM comments to explain what I did.

REM Printing the Prime numbers up to 10,000 (maxcheck)
REM Winkleink - 2012
REM Just print the 1st 3 Primes
print 1
print 2
print 3
REM x is what we are checking set x to the next biggest odd number
x=5
REM number up to which we will check for primes
maxcheck = 10000
while x < maxcheck
REM Start the checking with 3 as 1 isn't valid and we are only checking odd number
i = 3
REM Set indicator if prime to 1 (means prime)
isprime =1
REM We only have to check odd numbers up to the Square Root of X as any number that will divide into X evenly will be made up of a number below SQR(x) and 1 above SQR(x)
while i <= int(sqr(x))
REM Check not Prime by seeing if there is a remainder if there is no remainder set isprime to 0
if x/i = int(x/i) then isprime=0
REM If not prime then set i to be above the while loop
if isprime = 0 then i= int(sqr(x))
REM Increment i by 2 as only need to divide by odd
i = i +2
endwhile
REM If isprime is still 1 then it is a prime number
if isprime=1 then print x
REM Increment x by 2,again even numbers won't be prime
x = x +2
endwhile

It was great fun to do and really brought back memories of sitting in the computer room in school watching as it slowly printed out the results.  A bit faster today.

And here is a video of it working.

As always.  Code is rough and just done for fun.  If you know a better way to calculate primes let me know in the comments.