Mon, 24 Oct 2022 10:52:19 +0300
Added type for numerical errors
0 | 1 | ///! This module implements some arithmetic functions that are valid in a ‘const context”, i.e., |
2 | ///! can be computed at compile-time. | |
3 | ||
4 | /// Calculate $n!$. | |
5 | /// (The version in the crate `num_integer` deesn't currently work in a `const` context. | |
6 | pub const fn factorial(n : usize) -> usize { | |
7 | const fn f(i : usize, a : usize) -> usize { | |
8 | if i==0 { a } else { f(i-1, i*a) } | |
9 | } | |
10 | f(n, 1) | |
11 | } | |
12 | ||
13 | /// Calculate $\nchoosek{n}{k}$. | |
14 | /// (The version in the crate `num_integer` deesn't currently work in a `const` context. | |
15 | pub const fn binomial(n : usize, k : usize) -> usize { | |
16 | factorial(n)/(factorial(n-k)*factorial(k)) | |
17 | } | |
18 | ||
19 | /// Calculate $n^k$. | |
20 | /// (The version in the crate `num_integer` deesn't currently work in a `const` context. | |
21 | pub const fn pow(n : usize, k : usize) -> usize { | |
22 | const fn pow_accum(n : usize, k : usize, accum : usize) -> usize { | |
23 | if k==0 { accum } else { pow_accum(n, k-1, accum*n) } | |
24 | } | |
25 | pow_accum(n, k, 1) | |
26 | } |