feat(25): complete 1000-digit fibonacci number

This commit is contained in:
newt 2024-10-09 18:10:13 +01:00
parent 508f898e44
commit 2c5ed7a6d3
3 changed files with 69 additions and 2 deletions

View file

@ -17,7 +17,7 @@ Here is a [link to my profile](https://projecteuler.net/progress=newtykins).
## Challenge Completion
### 27 out of 100 public challenges completed.
### 28 out of 100 public challenges completed.
- [x] 1 - [Multiples of 3 or 5](src/bin/1.rs)
- [x] 2 - [Even Fibonacci numbers](src/bin/2.rs)
@ -43,7 +43,7 @@ Here is a [link to my profile](https://projecteuler.net/progress=newtykins).
- [x] 22 - [Names scores](src/bin/22.rs)
- [x] 23 - Non-abundant sums
- [x] 24 - Lexicographic permutations
- [ ] 25 - 1000-digit Fibonacci number
- [x] 25 - 1000-digit Fibonacci number
- [ ] 26 - Reciprocal cycles
- [x] 27 - [Quadratic primes](src/bin/27.rs)
- [ ] 28 - Number spiral diagonals

64
src/bin/25.rs Normal file
View file

@ -0,0 +1,64 @@
/*
Problem 25 - $1000$-digit Fibonacci Number
The Fibonacci sequence is defined by the recurrence relation:
$F_n = F_{n - 1} + F_{n - 2}$, where $F_1 = 1$ and $F_2 = 1$.
Hence the first $12$ terms will be:
\begin{align}
F_1 &= 1\\
F_2 &= 1\\
F_3 &= 2\\
F_4 &= 3\\
F_5 &= 5\\
F_6 &= 8\\
F_7 &= 13\\
F_8 &= 21\\
F_9 &= 34\\
F_{10} &= 55\\
F_{11} &= 89\\
F_{12} &= 144
\end{align}
The $12$th term, $F_{12}$, is the first term to contain three digits.
What is the index of the first term in the Fibonacci sequence to contain $1000$ digits?
*/
fn fibonacci_with_digits(digits: usize) -> usize {
let mut antepenultimate = vec![1];
let mut previous = vec![1];
let mut index = 2;
while previous.len() < digits {
let mut current = vec![0; previous.len().max(antepenultimate.len())];
let mut carry = 0;
for i in 0..current.len() {
let sum = if i < antepenultimate.len() {
antepenultimate[i]
} else {
0
} + if i < previous.len() { previous[i] } else { 0 }
+ carry;
current[i] = sum % 10;
carry = sum / 10;
}
while carry > 0 {
current.push(carry % 10);
carry /= 10;
}
antepenultimate = previous;
previous = current;
index += 1;
}
index
}
pub fn main() {
let index: usize = fibonacci_with_digits(1000);
println!(
"The index of the first term in the Fibonacci sequence to contain 1000 digits is {}!",
index
);
}

View file

@ -56,6 +56,8 @@ mod twenty_two;
mod two;
#[path = "../bin/24.rs"]
mod twenty_four;
#[path = "../bin/25.rs"]
mod twenty_five;
pub async fn execute(
problem: Option<u8>,
@ -99,6 +101,7 @@ pub async fn execute(
21 => twenty_one::main(),
23 => twenty_three::main(),
24 => twenty_four::main(),
25 => twenty_five::main(),
_ => {
exists = false;
println!(