diff options
| author | David Czihak <git@dcz.at> | 2026-05-09 13:01:50 +0200 |
|---|---|---|
| committer | David Czihak <git@dcz.at> | 2026-05-09 13:01:50 +0200 |
| commit | 4b6f66fd512c254b5a82220dc77411fe391dd258 (patch) | |
| tree | 7d77d7966e9ad2e296986ea8cfeb607088028195 /examples/test-suite/src/math.zig | |
| parent | 64e9c56fc665972fdde5234c4fb2f2a882e237dc (diff) | |
Chore: Rework examples for thorough extension testing
Diffstat (limited to 'examples/test-suite/src/math.zig')
| -rw-r--r-- | examples/test-suite/src/math.zig | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/examples/test-suite/src/math.zig b/examples/test-suite/src/math.zig new file mode 100644 index 0000000..ef870ce --- /dev/null +++ b/examples/test-suite/src/math.zig @@ -0,0 +1,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)); +} |
