Rebol3 Code Examplex
Almost prime
Detect numbers with a specific count of prime factors.
Rebol [
title: "Rosetta code: Almost prime"
file: %Almost_prime.r3
url: https://rosettacode.org/wiki/Almost_prime
]
;- Prime Factorisation --------------------------------------------------
prime-factors: function [
"Returns a block of prime factors for N (with repetition)."
n [integer!]
][
factors: clear []
d: 2
while [(d * d) <= n][ ;; trial-divide
while [zero? n % d][ ;; d divides n → record it and reduce n
append factors d
n: n / d
]
++ d ;; advance to next candidate divisor
]
if n > 1 [append factors n] ;; leftover n > 1 must itself be prime
factors
]
;- Almost-Prime Filter --------------------------------------------------
almost-prime: function [
"Returns first list-len integers with exactly k prime factors"
k [integer!] list-len [integer!]
][
result: copy []
n: 2
while [list-len > length? result][
if k = length? prime-factors n [append result n]
++ n
]
result
]
;- Main -----------------------------------------------------------------
;; Print the first 10 K-almost-primes for K = 1 through 5.
repeat k 5 [
prin rejoin ["k: " k " => "]
print almost-prime k 10
]Output:
k: 1 => 2 3 5 7 11 13 17 19 23 29
k: 2 => 4 6 9 10 14 15 21 22 25 26
k: 3 => 8 12 18 20 27 28 30 42 44 45
k: 4 => 16 24 36 40 54 56 60 81 84 88
k: 5 => 32 48 72 80 108 112 120 162 168 176