aboutsummaryrefslogtreecommitdiff
path: root/examples/test-suite/src/math.zig
blob: ef870ce464c43512ca1383e8a9aaae4b37976d22 (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
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
61
62
63
64
65
66
67
68
69
70
const std = @import("std");

pub fn factorial(n: u64) u64 {
    if (n == 0) return 1;
    return n * factorial(n - 1);
}

pub fn isPrime(n: u64) bool {
    if (n < 2) return false;
    if (n == 2) return true;
    if (n % 2 == 0) return false;
    var i: u64 = 3;
    while (i * i <= n) : (i += 2) {
        if (n % i == 0) return false;
    }
    return true;
}

pub fn gcd(a: u64, b: u64) u64 {
    var x = a;
    var y = b;
    while (y != 0) {
        const t = y;
        y = x % y;
        x = t;
    }
    return x;
}

// ── Tests with "math: " prefix ────────────────────────────────────────────────
// Run all:        zig build test
// Run math only:  zig build test -- --test-filter "math:"

test "math: factorial base cases" {
    try std.testing.expectEqual(@as(u64, 1), factorial(0));
    try std.testing.expectEqual(@as(u64, 1), factorial(1));
    try std.testing.expectEqual(@as(u64, 2), factorial(2));
}

test "math: factorial larger values" {
    try std.testing.expectEqual(@as(u64, 120), factorial(5));
    try std.testing.expectEqual(@as(u64, 5040), factorial(7));
    try std.testing.expectEqual(@as(u64, 3628800), factorial(10));
}

test "math: isPrime small primes" {
    try std.testing.expect(isPrime(2));
    try std.testing.expect(isPrime(3));
    try std.testing.expect(isPrime(5));
    try std.testing.expect(isPrime(97));
}

test "math: isPrime composites and edge cases" {
    try std.testing.expect(!isPrime(0));
    try std.testing.expect(!isPrime(1));
    try std.testing.expect(!isPrime(4));
    try std.testing.expect(!isPrime(100));
}

test "math: gcd basics" {
    try std.testing.expectEqual(@as(u64, 6), gcd(12, 18));
    try std.testing.expectEqual(@as(u64, 1), gcd(7, 13));
    try std.testing.expectEqual(@as(u64, 5), gcd(5, 0));
    try std.testing.expectEqual(@as(u64, 5), gcd(0, 5));
}

// Deliberately named differently — filtered OUT by "--test-filter math:"
test "number theory: Euclid handles equal inputs" {
    try std.testing.expectEqual(@as(u64, 42), gcd(42, 42));
}