06-03-2003, 02:47 AM
Let's try it in the spanish way:
The best way to calculate a square root is not calculating it at all..
No divisions or MOD either..
It calculates 16384 primes in 3 seconds in my P4 1,4... to display them it takes a little longer.
The best way to calculate a square root is not calculating it at all..
No divisions or MOD either..
It calculates 16384 primes in 3 seconds in my P4 1,4... to display them it takes a little longer.
Code:
CLS
PRINT "PRIME CALCULATOR BY ANTONI GUAL"
'indicate in stor how many primes you want
CONST stor = 16383 'That's the maximum;you may have to set the /ah switch
REDIM pr(stor) AS LONG
REDIM pr1(stor) AS LONG
REDIM pr2(stor) AS LONG
'pr saves primes found
'pr1 saves primes multiplied by factor pr2
'We save pr2 to stop scanning the array if pr2<pr, this indicates that
' pr> sqr(test&) without having to calculate the square root.
'
'pr() saves primes, pr1()=pr()*pr2()
'init the tables with 2 and test our first candidate, 3
pr(0) = 2
pr1(0) = 2
pr2(0) = 1
maxx& = 2
ind% = 0
test& = 3
t! = TIMER
DO
isprime% = -1
FOR i% = 0 TO ind%
WHILE pr1(i%) < test&: pr1(i%) = pr1(i%) + pr(i%): pr2(i%) = pr2(i%) + 1: WEND
IF pr2(i%) <= pr(i%) THEN EXIT FOR
IF pr1(i%) = test& THEN isprime% = 0: EXIT FOR
NEXT
IF isprime% THEN
ind% = ind% + 1
IF (ind% AND 1023) = 0 THEN PRINT ind%; "th prime is:"; test&
pr(ind%) = test&
pr1(ind%) = test&
pr2(ind%) = 1
END IF
test& = test& + 1
LOOP UNTIL ind% = stor
'That's all!
t1! = TIMER - t!
PRINT : PRINT stor + 1; " primes found in"; t1!; " seconds."; : INPUT "Want to print them all? (Y/N)"; a$
IF UCASE$(a$) <> "Y" THEN END
t! = TIMER
'array full, print it...
PRINT
FOR i% = 0 TO stor
PRINT pr(i%),
NEXT
PRINT : PRINT stor + 1; " primes printed in "; TIMER - t!; "Not so fast..."
ERASE pr, pr1, pr2
Antoni