/
Main.ds
60 lines (50 loc) · 1.6 KB
/
Main.ds
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
-- Almost Prime
-- https://rosettacode.org/wiki/Almost_prime
--
-- A k-Almost-prime is a natural number 'n' that is the product of 'k'
-- (possibly identical) primes. So, for example, 1-almost-primes, where
-- k=1, are the prime numbers themselves; 2-almost-primes are the semiprimes.
-- The task is to write a function/method/subroutine/... that generates
-- k-almost primes and use it to create a table here of the first ten
-- members of k-Almost primes for 1<=K<=5.
--
module Main
import System.IO.Console
import Class.Category
import Class.Show
import Data.Function
import Data.Numeric
import Data.Stream
import Data.Tuple
import Data.List
import Data.Text
where
-- | A stream of prime numbers.
primes (c0: Nat): Stream Nat Nat
= sfilter isPrime $ senumFrom 2
-- | Check if a number is prime.
-- Use Wilson's theorem to check for primality, being sure to take
-- the mod of the running sum to avoid integer overflow.
isPrime (n: Nat): Bool
= foldl (λacc x -> rem (x * acc) n) 1 (enumFromTo 1 (n - 1))
== (n - 1)
-- | A stream of k-almost-prime numbers.
kPrimes (k: Nat): Stream Nat Nat
= sfilter (isKPrime k) (senumFrom 2)
-- | Check if some number is k-almost-prime.
isKPrime (k n: Nat): Bool
| k == 1
= isPrime n
| otherwise
= sany $ smap (isKPrime (k - 1))
$ smap fst
$ sfilter (eq 0 ∘ snd)
$ smap (divMod n)
$ stakeWhile (λx -> x < n)
$ primes 2
main ()
= forS (enumFromTo 1 5) $ λk
-> do write $ "k = " % show k % ": "
forS (listOfStream $ stake 10 $ kPrimes k) $ λx
-> write $ show x % " "
write "\n"