#include #include #include "minitest.h" #include "intmath.h" int int_pown(unsigned int base, unsigned int exp) { int res = 1; while (exp > 0) { res *= base; exp--; } return res; } int int_logn(unsigned int base, unsigned int a) { unsigned int exp = 1; int res = (int) base; int lastres = res - 1; while ((res < a) && (lastres < res)) { lastres = res; res *= base; exp++; } return exp; } unsigned long long ull_pown(unsigned int base, unsigned int exp) { unsigned long long res = 1; while (exp > 0) { res *= base; exp--; } return res; } int int_pow10(unsigned int exp) { return int_pown(10, exp); } int int_floor(int x, int precision) { int sign = (x < 0) * -2 + 1; x *= sign; int iterations = 0; while (x > int_pow10(precision)) { x /= 10; iterations++; } return (x + (sign == -1)) * int_pow10(iterations) * sign; } int int_ceil(int x, int precision) { return -int_floor(-x, precision); } int int_min(int a, int b) { return (a < b) * a + (b <= a) * b; } int int_max(int a, int b) { return (a > b) * a + (b >= a) * b; } char* test_pown() { mt_assert_eq(int_pown(2, 5), 32); mt_assert_eq(int_pown(3, 3), 27); mt_assert_eq(int_pown(9, 0), 1); return 0; } char* test_pow10() { mt_assert_eq(int_pow10(3), 1000); mt_assert_eq(int_pow10(0), 1); return 0; } char* test_floor() { mt_assert_eq(int_floor(34128, 2), 34000); mt_assert_eq(int_floor(-34128, 3), -34200); mt_assert_eq(int_floor(-9999, 3), -10000); mt_assert_eq(int_floor(9999, 3), 9990); mt_assert_eq(int_floor(0, 1), 0); return 0; } char* test_ceil() { mt_assert_eq(int_ceil(44212, 3), 44300); mt_assert_eq(int_ceil(-44212, 3), -44200); mt_assert_eq(int_ceil(-9999, 3), -9990); mt_assert_eq(int_ceil(9999, 3), 10000); mt_assert_eq(int_ceil(0, 1), 0); return 0; } char* test_min() { mt_assert_eq(int_min(2, 6), 2); mt_assert_eq(int_min(4, 1), 1); mt_assert_eq(int_min(10, 10), 10); return 0; } char* test_max() { mt_assert_eq(int_max(3, 7), 7); mt_assert_eq(int_max(4, 1), 4); mt_assert_eq(int_max(10, 10), 10); return 0; } void intmath_tests() { mt_run_test(test_pown); mt_run_test(test_pow10); mt_run_test(test_floor); mt_run_test(test_ceil); mt_run_test(test_min); mt_run_test(test_max); }