Browse Source

problem 25

canon
Hazel Levine 1 year ago
parent
commit
3caf693ecf
2 changed files with 36 additions and 0 deletions
  1. +1
    -0
      Cargo.toml
  2. +35
    -0
      src/bin/prob25.rs

+ 1
- 0
Cargo.toml View File

@ -9,3 +9,4 @@ edition = "2018"
[dependencies]
num-bigint = "0.2"
num-traits = "0.2"
rug = "1.7.0"

+ 35
- 0
src/bin/prob25.rs View File

@ -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)
);
}

Loading…
Cancel
Save