diff --git a/benchmarks/core/sum-check.bril b/benchmarks/core/sum-check.bril new file mode 100644 index 000000000..ccdcc6246 --- /dev/null +++ b/benchmarks/core/sum-check.bril @@ -0,0 +1,38 @@ +# compute the sum of [1, n] by both loop and formula +# and compare them to see if the result is the same + +# ARGS: 1000 +@main(n: int) { + first: int = call @sum_by_loop n; + second: int = call @sum_by_formula n; + isSame: bool = eq first second; + print first; + print second; + print isSame; +} + +@sum_by_loop(n: int): int { + one: int = const 1; + sum: int = const 0; + i: int = const 1; + +.for_start: + con: bool = le i n; + br con .for .end; +.for: + sum: int = add sum i; + i: int = add i one; + jmp .for_start; +.end: + ret sum; +} + +# sum = (1 + n) * n / 2 +@sum_by_formula(n: int): int { + one: int = const 1; + two: int = const 2; + n_1: int = add one n; + multi: int = mul n_1 n; + sum: int = div multi two; + ret sum; +} \ No newline at end of file diff --git a/benchmarks/core/sum-check.out b/benchmarks/core/sum-check.out new file mode 100644 index 000000000..cbdb122dc --- /dev/null +++ b/benchmarks/core/sum-check.out @@ -0,0 +1,3 @@ +500500 +500500 +true diff --git a/benchmarks/core/sum-check.prof b/benchmarks/core/sum-check.prof new file mode 100644 index 000000000..d5196d885 --- /dev/null +++ b/benchmarks/core/sum-check.prof @@ -0,0 +1 @@ +total_dyn_inst: 5018 diff --git a/docs/tools/bench.md b/docs/tools/bench.md index bbce89d1f..5c54f4cbb 100644 --- a/docs/tools/bench.md +++ b/docs/tools/bench.md @@ -59,6 +59,7 @@ The current benchmarks are: * `sieve`: Print all prime numbers up to *n* using the [Sieve of Eratosthenes][sievee]. * `sqrt`: Implements the [Newton–Raphson Method][newton] of approximating the square root of a number to arbitrary precision * `sum-bit`: Print the number of 1-bits in the binary representation of the input integer. +* `sum-check`: Compute the sum of [1, n] by both loop and formula, and check if the result is the same. * `sum-divisors`: Prints the positive integer divisors of the input integer, followed by the sum of the divisors. * `sum-sq-diff`: Output the difference between the sum of the squares of the first *n* natural numbers and the square of their sum. * `totient`: Computes [Euler's totient function][totient] on an input integer *n*.