| 1 | /* @title: Integer Arithmetic Functions */ |
| 2 | #pragma once |
| 3 | #include <compiler/core.h> |
| 4 | #include <stddef.h> |
| 5 | #include <stdint.h> |
| 6 | |
| 7 | static inline cc_constfn size_t gcd(size_t a, size_t b) { |
| 8 | while (b) { |
| 9 | size_t t = b; |
| 10 | b = a % b; |
| 11 | a = t; |
| 12 | } |
| 13 | return a; |
| 14 | } |
| 15 | |
| 16 | static inline cc_constfn size_t lcm(size_t a, size_t b) { |
| 17 | return (a / gcd(a, b)) * b; |
| 18 | } |
| 19 | |
| 20 | static inline cc_constfn size_t ipow(size_t base, int32_t exp) { |
| 21 | size_t result = 1; |
| 22 | while (exp > 0) { |
| 23 | if (exp & 1) |
| 24 | result *= base; |
| 25 | exp >>= 1; |
| 26 | base *= base; |
| 27 | } |
| 28 | return result; |
| 29 | } |
| 30 | |
| 31 | #define isqrt(n_) \ |
| 32 | ({ \ |
| 33 | typeof(n_) __isqrt_val = (n_); \ |
| 34 | typeof(n_) __isqrt_res = 0; \ |
| 35 | if (__isqrt_val > 0) { \ |
| 36 | typeof(n_) __isqrt_x0 = __isqrt_val / 2; \ |
| 37 | if (__isqrt_x0 == 0) { \ |
| 38 | __isqrt_res = 1; \ |
| 39 | } else { \ |
| 40 | typeof(n_) __isqrt_x1 = \ |
| 41 | (__isqrt_x0 + __isqrt_val / __isqrt_x0) / 2; \ |
| 42 | while (__isqrt_x1 < __isqrt_x0) { \ |
| 43 | __isqrt_x0 = __isqrt_x1; \ |
| 44 | __isqrt_x1 = (__isqrt_x0 + __isqrt_val / __isqrt_x0) / 2; \ |
| 45 | } \ |
| 46 | __isqrt_res = __isqrt_x0; \ |
| 47 | } \ |
| 48 | } \ |
| 49 | __isqrt_res; \ |
| 50 | }) |
| 51 | |