News:

PlayBASIC2DLL V0.99 Revision I Commercial Edition released! - Convert PlayBASIC programs to super fast Machine Code. 

Main Menu

Calc Prime Numbers

Started by kevin, November 07, 2008, 05:02:54 AM

Previous topic - Next topic

kevin

Calc Prime Numbers

 While sifting through some old PlayBASIC code snippets, I ran into this one.  The code calc's the prime numbers from zero to a given range.  I'm not sure why I wrote this now, I think it was somebody here. Anyway, there's two versions one's quicker than the other.  Neither are very pretty thought.


PlayBASIC Code: [Select]
;*=------------------------------------------------------------------------=*   
;
; >> Calc Prime Numbers <<
;
; Code By: Kevin Picone
;
; Date: 2/6/2005
;
; Copyright 2005 by Kevin Picone, All Rights Reserved.
;
;*=-------------------------------------------------------------------------=*
;
; About:
; ======
;
; This example shows a couple of ways to generate prime numbers. I remember
; writing it for somebody, anyway, here it is.
;
;*=--------------------------------------------------------------------------=*

max=2000


Do
Cls 0
inc frames
Dim table(max)

t=timer()
Result=CalcprimesORIG(table(),Max)
t=timer()-t
tt1#=tt1#+T
ShowVals(Result-1)
print "Time:"+str$(tt1#/frames)
print "Results:"+str$(result)

Dim table(max)

t=timer()
Result=Calcprimes(table(),Max)
t=timer()-t
tt2#=tt2#+T
ShowVals(Result-1)
print "Time:"+str$(tt2#/frames)
print "Results:"+str$(result)

sync
loop



Function CalcPRimes(Results(),Max)

; Pre-seed 1 & 2 as primes
results(index)=1
inc index
results(index)=2
inc index

For PrimeTest=3 to max step 2
PrimeMax=Sqrt(PrimeTEst)
if ((PrimeTEst/2)*2)<>Primetest
Found=True
For TestDiv=3 to PrimeMax step 2
if ((PrimeTest/TestDiv)*TestDiv)=PrimeTest
Found=False
exit
endif
next
if Found=true
results(index)=PrimeTest
inc index
endif
endif
next

EndFUnction index




Function CalcPRimesORIG(Results(),Max)

; Pre-seed 1 & 2 as primes
results(index)=1
inc index
results(index)=2
inc index

For PrimeTest=3 to max
Found=True
For TestDiv=2 to PrimeTest-1
if ((PrimeTest/TestDiv)*TestDiv)=PrimeTest
Found=False
exit
endif
next
if Found=true
results(index)=PrimeTest
inc index
endif
next

EndFUnction index


Function ShowVals(Results)
t$=""
For lp=0 to results-1
t$=t$+digits$(table(lp),5)+","
inc c
if c>15
print trimright$(t$,",")
t$=""
c =0
endif
next
print trimright$(t$,",")
#print t$
EndFunction






thaaks

I remember doing that as a homework in Elan (similar to Pascal) at university 25 years ago  ;D