Skip to content

Instantly share code, notes, and snippets.

@lovasoa
Created April 11, 2019 09:40
Show Gist options
  • Save lovasoa/d5a795a1d487378e89850902d58e7e77 to your computer and use it in GitHub Desktop.
Save lovasoa/d5a795a1d487378e89850902d58e7e77 to your computer and use it in GitHub Desktop.
generic factorial function in rust
use num::{One, BigUint}; // 0.2.0
use std::ops::{MulAssign, AddAssign};
fn fac<T>(n: T) -> T
where T: One + AddAssign + Ord,
for <'a> T : MulAssign<&'a T> {
let mut r = T::one();
let mut i = T::one();
while i <= n {
r *= &i;
i += T::one();
}
r
}
fn main() {
let n : u32 = 999;
let r = fac(BigUint::from(n));
println!("fac({}) = {}", n, r);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment