diff --git a/Cargo.toml b/Cargo.toml index ab780ff..b674eee 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,3 +9,4 @@ edition = "2018" [dependencies] num-bigint = "0.2" num-traits = "0.2" +rug = "1.7.0" diff --git a/src/bin/prob25.rs b/src/bin/prob25.rs new file mode 100644 index 0000000..1923030 --- /dev/null +++ b/src/bin/prob25.rs @@ -0,0 +1,35 @@ +// Problem 25: +// +// What is the index of the first term in the Fibonacci sequence to contain +// 1000 digits? + +extern crate rug; + +use rug::{ops::Pow, Float, Integer}; + +const PHI: f64 = 1.618_033_988_749_895; + +// https://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression +// uses change of base as GMP doesn't implement log of a certain base +fn fib_idx(n: Integer) -> Integer { + let phi = Float::with_val(64, PHI); + + let to_ln: Float = n * Float::with_val(64, 5f64.sqrt()) + 0.5; + let ln_x: Float = to_ln.ln(); + let ln_phi: Float = phi.ln(); + + (ln_x / ln_phi).floor().to_integer().unwrap() + 1 +} + +fn compute(n: u32) -> Integer { + let upper_limit: Integer = Integer::from(10).pow(n - 1); + + fib_idx(upper_limit) +} + +fn main() { + println!( + "the index of the smallest fibonacci number with 1000 digits is: {}", + compute(1000) + ); +}