Search code examples
rustfactorial

failing to resolve as Trait in Rust in a factorial function


In case the reader doesn't' know the factorial function is written to take a u64 type and I'm trying to use a BigUint instead to get bigger numbers with the factorial function.

I'm trying to cast an integer into a BigUint in Rust this is the code I'm trying to change:

pub fn factorial_iterative(n: u64) -> u64 {
    (1..n+1).fold(1, |p, n| p*n)
}

I've just been following rust's handy auto correction and I've come up with this:

extern crate num;
use num::BigUint;

pub fn factorial_iterative(n: BigUint) -> BigUint {
    (1..n+1).fold(1 as <num::BigUint as Trait>::to_u64, |p, n| p*n)
}

but now its throwing me the error: failed to resolve use of undeclared type or module Trait

What do I need to add or change to make this work?


Solution

  • The correct way to get a 1 would be

    use num::BigUint;
    use num::One;
    
    pub fn factorial_iterative(n: u64) -> BigUint {
        (1..=n).fold(BigUint::one(), |p, n| p*n)
    }
    

    You can't do ranges with the BigUint, so you have to use u64 ranges. You can use the ..= to get inclusive ranges.use crate::num::One; is needed to use ::one() because its implemented in the One Trait which needs to be in scope.