aboutsummaryrefslogtreecommitdiff
path: root/examples/wilsonp.micro
blob: 9bc626fb67025f458d0e6427828200d919db9065 (plain)
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
//
// Show prime numbers using the Wilson theorem: https://en.wikipedia.org/wiki/Wilson%27s_theorem#Primality_tests
//
// Also using a recursive function for the loops
//

def loop(from number, to number, fn func (number) bool) {
    if from > to {
        return;
    }
    if !fn(from) {
        return;
    }
    return loop(from + 1, to, fn);
}

def wilsonPrime(n number) bool {
    var acc number = 1;
    def fact(i number) bool {
        acc = (acc * i) % n;
        return acc != 0;
    }

    loop(2, n - 1, fact);

    if acc == n - 1 {
        println(n, " is prime");
    }

    return true;
}

loop(2, 100, wilsonPrime);