prog8/examples/primes.p8

54 lines
1.3 KiB
Plaintext
Raw Normal View History

%import textio
%zeropage basicsafe
2019-01-27 00:02:45 +00:00
; Note: this program can be compiled for multiple target systems.
2019-07-29 21:11:13 +00:00
main {
2019-01-27 00:02:45 +00:00
bool[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() {
sys.memset(sieve, 256, 0) ; clear the sieve, to reset starting situation on subsequent runs
2019-01-27 00:02:45 +00:00
; calculate primes
2020-08-27 16:10:22 +00:00
txt.print("prime numbers up to 255:\n\n")
2019-02-25 00:37:05 +00:00
ubyte amount=0
repeat {
2019-01-27 00:02:45 +00:00
ubyte prime = find_next_prime()
if prime==0
break
2020-08-27 16:10:22 +00:00
txt.print_ub(prime)
txt.print(", ")
2019-02-25 00:08:10 +00:00
amount++
2019-01-27 00:02:45 +00:00
}
2021-01-08 15:56:17 +00:00
txt.nl()
2020-08-27 16:10:22 +00:00
txt.print("number of primes (expected 54): ")
txt.print_ub(amount)
2021-01-08 15:56:17 +00:00
txt.nl()
2020-11-22 17:17:43 +00:00
; test_stack.test()
2019-01-27 00:02:45 +00:00
}
sub find_next_prime() -> ubyte {
2019-02-25 00:37:05 +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
2019-01-27 00:02:45 +00:00
}
2022-05-23 19:24:36 +00:00
return candidate_prime
2019-01-27 00:02:45 +00:00
}
}