aboutsummaryrefslogtreecommitdiff
path: root/examples/test-suite/src/math.zig
diff options
context:
space:
mode:
Diffstat (limited to 'examples/test-suite/src/math.zig')
-rw-r--r--examples/test-suite/src/math.zig70
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));
+}