Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

failing to resolve as Trait in Rust in a factorial function

Tags:

rust

factorial

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?

like image 780
Whitequill Riclo Avatar asked Dec 20 '25 19:12

Whitequill Riclo


1 Answers

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.

like image 193
Unlikus Avatar answered Dec 23 '25 21:12

Unlikus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!