2020-09-20 23:49:36 +02:00
|
|
|
%import textio
|
2019-02-03 00:14:56 +01:00
|
|
|
%zeropage basicsafe
|
2019-01-27 01:02:45 +01:00
|
|
|
|
2023-06-03 19:14:45 +02:00
|
|
|
; Note: this program can be compiled for multiple target systems.
|
2020-09-20 23:49:36 +02:00
|
|
|
|
2019-07-29 23:11:13 +02:00
|
|
|
main {
|
2019-01-27 01:02:45 +01:00
|
|
|
|
2022-07-08 21:50:32 +02:00
|
|
|
bool[256] sieve
|
2019-02-25 01:37:05 +01:00
|
|
|
ubyte candidate_prime = 2 ; is increased in the loop
|
2019-01-27 01:02:45 +01:00
|
|
|
|
|
|
|
sub start() {
|
2021-01-08 01:05:26 +01:00
|
|
|
sys.memset(sieve, 256, false) ; clear the sieve, to reset starting situation on subsequent runs
|
2019-01-27 01:02:45 +01:00
|
|
|
|
|
|
|
; calculate primes
|
2020-08-27 18:10:22 +02:00
|
|
|
txt.print("prime numbers up to 255:\n\n")
|
2019-02-25 01:37:05 +01:00
|
|
|
ubyte amount=0
|
2020-07-25 16:25:02 +02:00
|
|
|
repeat {
|
2019-01-27 01:02:45 +01:00
|
|
|
ubyte prime = find_next_prime()
|
|
|
|
if prime==0
|
|
|
|
break
|
2020-08-27 18:10:22 +02:00
|
|
|
txt.print_ub(prime)
|
|
|
|
txt.print(", ")
|
2019-02-25 01:08:10 +01:00
|
|
|
amount++
|
2019-01-27 01:02:45 +01:00
|
|
|
}
|
2021-01-08 16:56:17 +01:00
|
|
|
txt.nl()
|
2020-08-27 18:10:22 +02:00
|
|
|
txt.print("number of primes (expected 54): ")
|
|
|
|
txt.print_ub(amount)
|
2021-01-08 16:56:17 +01:00
|
|
|
txt.nl()
|
2020-11-22 18:17:43 +01:00
|
|
|
|
|
|
|
; test_stack.test()
|
2019-01-27 01:02:45 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
sub find_next_prime() -> ubyte {
|
2019-02-25 01:37:05 +01:00
|
|
|
|
2019-01-27 18:33:21 +01: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-24 01:31:25 +02:00
|
|
|
uword multiple = candidate_prime
|
|
|
|
|
2019-01-27 18:33:21 +01:00
|
|
|
while multiple < len(sieve) {
|
2020-10-18 14:05:26 +02:00
|
|
|
sieve[lsb(multiple)] = true
|
2019-06-24 01:31:25 +02:00
|
|
|
multiple += candidate_prime
|
2019-01-27 01:02:45 +01:00
|
|
|
}
|
2022-05-23 21:24:36 +02:00
|
|
|
|
2019-01-27 18:33:21 +01:00
|
|
|
return candidate_prime
|
2019-01-27 01:02:45 +01:00
|
|
|
}
|
|
|
|
}
|