prog8/examples/test.p8

54 lines
1.3 KiB
Plaintext
Raw Normal View History

%import c64utils
%zeropage basicsafe
2020-07-26 22:32:59 +00:00
main {
2020-08-23 22:26:26 +00:00
ubyte[256] sieve
ubyte candidate_prime = 2 ; is increased in the loop
2020-07-26 21:32:20 +00:00
sub start() {
2020-08-23 22:26:26 +00:00
ubyte x
for x in 0 to 255 {
sieve[x] = 0
}
; memset(sieve, 256, false) ; clear the sieve, to reset starting situation on subsequent runs
2020-08-18 13:16:56 +00:00
2020-08-23 22:26:26 +00:00
; calculate primes
c64scr.print("prime numbers up to 255:\n\n")
ubyte amount=0
repeat {
ubyte prime = find_next_prime()
if prime==0
break
c64scr.print_ub(prime)
c64scr.print(", ")
amount++
}
c64.CHROUT('\n')
c64scr.print("number of primes (expected 54): ")
c64scr.print_ub(amount)
2020-08-23 16:32:53 +00:00
c64.CHROUT('\n')
2020-08-23 22:26:26 +00:00
}
sub find_next_prime() -> ubyte {
2020-08-23 16:32:53 +00:00
2020-08-23 22:26:26 +00:00
while sieve[candidate_prime] {
candidate_prime++
if candidate_prime==0
return 0 ; we wrapped; no more primes available in the sieve
}
; found next one, mark the multiples and return it.
sieve[candidate_prime] = true
uword multiple = candidate_prime
while multiple < len(sieve) {
sieve[lsb(multiple)] = true
multiple += candidate_prime
}
return candidate_prime
2020-07-25 23:32:27 +00:00
}
}