2022-02-22 20:07:19 +00:00
|
|
|
%import textio
|
2022-02-27 15:27:02 +00:00
|
|
|
%import test_stack
|
|
|
|
%zeropage basicsafe
|
2022-02-15 22:16:49 +00:00
|
|
|
|
2022-03-04 21:26:46 +00:00
|
|
|
; Note: this program is compatible with C64 and CX16.
|
|
|
|
|
2021-10-30 13:15:11 +00:00
|
|
|
main {
|
2022-03-04 21:26:46 +00:00
|
|
|
|
|
|
|
ubyte[256] sieve
|
|
|
|
ubyte candidate_prime = 2 ; is increased in the loop
|
|
|
|
|
2022-02-15 22:16:49 +00:00
|
|
|
sub start() {
|
2022-03-04 21:26:46 +00:00
|
|
|
sys.memset(sieve, 256, false) ; clear the sieve, to reset starting situation on subsequent runs
|
2022-02-27 15:27:02 +00:00
|
|
|
|
2022-03-04 21:26:46 +00:00
|
|
|
; calculate primes
|
|
|
|
txt.print("prime numbers up to 255:\n\n")
|
|
|
|
ubyte amount=0
|
|
|
|
repeat {
|
|
|
|
ubyte prime = find_next_prime()
|
|
|
|
if prime==0
|
|
|
|
break
|
|
|
|
txt.print_ub(prime)
|
|
|
|
txt.print(", ")
|
|
|
|
amount++
|
|
|
|
}
|
|
|
|
txt.nl()
|
|
|
|
txt.print("number of primes (expected 54): ")
|
|
|
|
txt.print_ub(amount)
|
|
|
|
txt.nl()
|
2022-02-25 22:48:39 +00:00
|
|
|
|
2022-03-04 21:26:46 +00:00
|
|
|
; test_stack.test()
|
2022-02-27 15:27:02 +00:00
|
|
|
}
|
2022-02-25 18:16:37 +00:00
|
|
|
|
2022-03-12 13:12:06 +00:00
|
|
|
sub derp() -> ubyte, ubyte {
|
|
|
|
return 0, 1
|
|
|
|
}
|
2022-02-27 15:27:02 +00:00
|
|
|
|
2022-03-04 21:26:46 +00:00
|
|
|
sub find_next_prime() -> ubyte {
|
|
|
|
|
|
|
|
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
|
2022-02-27 15:27:02 +00:00
|
|
|
|
2022-03-04 21:26:46 +00:00
|
|
|
|
|
|
|
while multiple < len(sieve) {
|
|
|
|
sieve[lsb(multiple)] = true
|
|
|
|
multiple += candidate_prime
|
|
|
|
}
|
|
|
|
return candidate_prime
|
|
|
|
}
|
2022-02-17 23:40:31 +00:00
|
|
|
}
|