Tue, 25 Oct 2022 23:05:40 +0300
Added NormExponent trait for exponents of norms
| 5 | 1 | /*! |
| 2 | Arithmetic functions that are valid in a ‘const context”, i.e., can be computed at compile-time. | |
| 3 | */ | |
| 0 | 4 | |
| 5 | 5 | /// Calculate $n!$. Valid in a const-context. |
| 6 | /// | |
| 7 | /// (The version in the crate `num_integer` deesn't currently work in a const-context.) | |
| 0 | 8 | pub const fn factorial(n : usize) -> usize { |
| 9 | const fn f(i : usize, a : usize) -> usize { | |
| 10 | if i==0 { a } else { f(i-1, i*a) } | |
| 11 | } | |
| 12 | f(n, 1) | |
| 13 | } | |
| 14 | ||
| 5 | 15 | /// Calculate $n \choose k$. Valid in a const-context. |
| 16 | /// | |
| 17 | /// (The version in the crate `num_integer` doesn't currently work in a const-context.) | |
| 0 | 18 | pub const fn binomial(n : usize, k : usize) -> usize { |
| 19 | factorial(n)/(factorial(n-k)*factorial(k)) | |
| 20 | } | |
| 21 | ||
| 5 | 22 | /// Calculate $n^k$. Valid in a const-context. |
| 23 | /// | |
| 24 | /// (The version in the crate `num_integer` doesn't currently work in a const-context.) | |
| 0 | 25 | pub const fn pow(n : usize, k : usize) -> usize { |
| 26 | const fn pow_accum(n : usize, k : usize, accum : usize) -> usize { | |
| 27 | if k==0 { accum } else { pow_accum(n, k-1, accum*n) } | |
| 28 | } | |
| 29 | pow_accum(n, k, 1) | |
| 30 | } |