2019-01-27 00:02:45 +00:00
|
|
|
%import c64utils
|
2019-02-02 23:14:56 +00:00
|
|
|
%zeropage basicsafe
|
2019-01-27 00:02:45 +00:00
|
|
|
|
|
|
|
~ main {
|
|
|
|
|
2019-01-27 17:33:21 +00:00
|
|
|
ubyte[256] sieve
|
2019-02-25 00:37:05 +00:00
|
|
|
ubyte candidate_prime = 2 ; is increased in the loop
|
2019-01-27 00:02:45 +00:00
|
|
|
|
|
|
|
sub start() {
|
2019-02-25 00:37:05 +00:00
|
|
|
memset(sieve, 256, false) ; clear the sieve, to reset starting situation on subsequent runs
|
2019-01-27 00:02:45 +00:00
|
|
|
|
|
|
|
; calculate primes
|
|
|
|
c64scr.print("prime numbers up to 255:\n\n")
|
2019-02-25 00:37:05 +00:00
|
|
|
ubyte amount=0
|
2019-01-27 00:02:45 +00:00
|
|
|
while true {
|
|
|
|
ubyte prime = find_next_prime()
|
|
|
|
if prime==0
|
|
|
|
break
|
|
|
|
c64scr.print_ub(prime)
|
|
|
|
c64scr.print(", ")
|
2019-02-25 00:08:10 +00:00
|
|
|
amount++
|
2019-01-27 00:02:45 +00:00
|
|
|
}
|
|
|
|
c64.CHROUT('\n')
|
2019-02-25 00:37:05 +00:00
|
|
|
c64scr.print("number of primes (expected 54): ")
|
2019-02-25 00:08:10 +00:00
|
|
|
c64scr.print_ub(amount)
|
|
|
|
c64.CHROUT('\n')
|
2019-01-27 00:02:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
sub find_next_prime() -> ubyte {
|
2019-02-25 00:37:05 +00:00
|
|
|
|
2019-01-27 17:33:21 +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
|
2019-06-23 23:31:25 +00:00
|
|
|
uword multiple = candidate_prime
|
|
|
|
|
|
|
|
|
2019-01-27 17:33:21 +00:00
|
|
|
while multiple < len(sieve) {
|
|
|
|
sieve[lsb(multiple)] = true
|
2019-06-23 23:31:25 +00:00
|
|
|
multiple += candidate_prime
|
2019-01-27 00:02:45 +00:00
|
|
|
}
|
2019-01-27 17:33:21 +00:00
|
|
|
return candidate_prime
|
2019-01-27 00:02:45 +00:00
|
|
|
}
|
|
|
|
}
|