I have the following code which, when given a number n, calculates the nth Fibonacci number.
pub fn fibonacci(n: i64) -> i64 {
fib_iter(1, 0, 0, 1, n)
}
fn fib_iter(a: i64, b: i64, p: i64, q: i64, count: i64) -> i64 {
if count == 0 {
return b;
}
if is_even(count) {
return fib_iter(a, b, p*p + q*q, 2*p*q + q*q, count / 2);
}
fib_iter(b*q + a*q + a*p, b*p + a*q, p, q, count - 1)
}
The problem is it only works for i64 while I would like it to be generic, so it works for any integral type.
I tried using the Integer trait from the num crate to make it generic:
pub fn fibonacci<T: Integer>(n: T) -> T {
fib_iter(1, 0, 0, 1, n)
}
fn fib_iter<T: Integer>(a: T, b: T, p: T, q: T, count: T) -> T {
if count.is_zero() {
return b;
}
if count.is_even() {
return fib_iter(a, b, p*p + q*q, 2*p*q + q*q, count / 2);
}
fib_iter(b*q + a*q + a*p, b*p + a*q, p, q, count - 1)
}
But it doesn’t like the use of any integer literals, for example:
66 | return fib_iter(a, b, p*p + q*q, 2*p*q + q*q, count / 2);
| ^ no implementation for `{integer} * T`
...
69 | fib_iter(b*q + a*q + a*p, b*p + a*q, p, q, count - 1)
| ^ expected type parameter `T`, found integer
I also tried doing something like the following:
let two: T = 2;
But same problem.
And same if I try using traits Mul, Div, Add, Sub etc.
1