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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
|
#include <stdlib.h>
#include <string.h>
#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;
}
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);
}
|