Implement a rust function to compute the nth element of the fibonacci sequence using…
- User
Implement a rust function to compute the nth element of the fibonacci sequence using matrix method
Assistant
Implement a rust function to compute the nth element of the fibonacci sequence using matrix method
To compute the nth element of the Fibonacci sequence using the matrix method in Rust, we'll use a 2x2 matrix to represent the Fibonacci sequence. The matrix method relies on the fact that the Fibonacci sequence can be represented by the following matrix multiplication:
| 1 1 | ^ n | F(n+1) F(n) |
| 1 0 | | F(n) F(n-1) |
To compute the nth element, we'll raise the matrix to the power of n. This can be done efficiently using exponentiation by squaring. Here's how you can implement it in Rust:
use num::BigInt;
use num::FromPrimitive;
use num::Zero;
use std::ops::Mul;
struct Matrix2x2 {
m: [[BigInt; 2]; 2],
}
impl Matrix2x2 {
fn new(m: [[BigInt; 2]; 2]) -> Self {
Matrix2x2 { m }
}
fn identity() -> Self {
Matrix2x2 {
m: [
[BigInt::from_u32(1).unwrap(), BigInt::zero()],
[BigInt::zero(), BigInt::from_u32(1).unwrap()],
],
}
}
fn mul(&self, other: &Matrix2x2) -> Matrix2x2 {
let mut result = [[BigInt::zero(); 2]; 2];
for i in 0..2 {
for j in 0..2 {
for k in 0..2 {
result[i][j] += &self.m[i][k] * &other.m[k][j];
}
}
}
Matrix2x2::new(result)
}
fn pow(&self, n: u32) -> Matrix2x2 {
if n == 0 {
return Matrix2x2::identity();
}
if n % 2 == 0 {
let half = self.pow(n / 2);
return half.mul(&half);
} else {
return self.mul(&self.pow(n - 1));
}
}
}
fn fibonacci_matrix(n: u32) -> BigInt {
let fib_matrix = Matrix2x2 {
m: [
[BigInt::from_u32(1).unwrap(), BigInt::from_u32(1).unwrap()],
[BigInt::from_u32(1).unwrap(), BigInt::zero()],
],
};
let result = fib_matrix.pow(n);
result.m[0][1].clone()
}
fn main() {
let n = 10; // Example: Compute the 10th Fibonacci number
let result = fibonacci_matrix(n);
println!("The {}th Fibonacci number is: {}", n, result);
}
This code defines a Matrix2x2 struct with methods for multiplication (mul) and exponentiation (pow). The fibonacci_matrix function computes the nth Fibonacci number by raising the Fibonacci matrix to the power of n and then extracting the appropriate element from the result matrix.
Note that this implementation uses BigInt from the num crate to handle large numbers, which is necessary for computing large Fibonacci numbers that exceed the capacity of primitive integer types. You'll need to add num to your Cargo.toml:
[dependencies]
num = "0.4"
This implementation is efficient for computing very large Fibonacci numbers because it uses exponentiation by squaring, which has a time complexity of O(log n).
Not yet included in a published release.