79 lines
2.4 KiB
Typst
79 lines
2.4 KiB
Typst
#let post_slug = "pe-p2"
|
|
#let post_preview_image = "image.png"
|
|
#let post_summary = "Solution to Project Euler Problem 2"
|
|
#let post_date = "2026-07-29"
|
|
|
|
#set math.mat(delim: "[")
|
|
|
|
= Project Euler Problem 2
|
|
|
|
== Statement
|
|
Each new term in the Fibonacci sequence is generated by adding the previous two terms.
|
|
|
|
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
|
|
|
|
== Exploration
|
|
|
|
|
|
The even terms in the sequence are:
|
|
#text(fill: white, html.frame(
|
|
$ cal(F) = {0, cancel(1), cancel(1), 2, cancel(3), cancel(5), 8, cancel(13), cancel(21), 34, cancel(55), ...} $
|
|
))
|
|
|
|
This can be computed quickly with code, some Fibonacci sequence equations would be interesting to derive.
|
|
|
|
Notice every 3rd number is even, as the previous two numbers are odd, which sums to even. A similar statement can be said about the odd numbers.
|
|
|
|
The Fibonacci sequence can be generated with the equation:
|
|
#text(fill: white, html.frame(
|
|
$ mat(cal(F)_i; cal(F)_(i+1)) = mat(0, 1; 1, 1) mat(cal(F)_(i-1); cal(F)_i) $
|
|
))
|
|
Then every third number can be defined with the equation:
|
|
#text(fill: white, html.frame(
|
|
$
|
|
&mat(cal(F)_(i+2); cal(F)_(i+3)) = mat(0, 1; 1, 1)^3 mat(cal(F)_(i-1); cal(F)_i)\
|
|
=>&mat(cal(F)_(i+2); cal(F)_(i+3)) = mat(1, 2; 2, 3) mat(cal(F)_(i-1); cal(F)_i)
|
|
$
|
|
))
|
|
Also something interesting I noticed for #text(fill: white, html.frame($cal(F) = {0, 1, 1, 2, 3, 5, 8, ...} (cal(F)_0 = 0, i>= 1)$)) is:
|
|
#text(fill: white, html.frame(
|
|
$
|
|
mat(0, 1; 1, 1)^i = mat(cal(F)_(i-1), cal(F)_(i); cal(F)_(i), cal(F)_(i+1))
|
|
$
|
|
))
|
|
|
|
Playing with that leads to the similar equation
|
|
|
|
#text(fill: white, html.frame(
|
|
[$cal(F)_(i+j) = cal(F)_(i) cal(F)_(j+1) + cal(F)_(i-1) cal(F)_(j)$,\ thus $cal(F)_(i+3) = 3cal(F)_i + 2cal(F)_(i-1)$]
|
|
))
|
|
|
|
An equation to represent this problem is as follows, however this would need a computer to finish in reasonable time.
|
|
#text(fill: white, html.frame(
|
|
$
|
|
sum_(i=1)^(n: cal(F)_(3n)<4 times 10^6) cal(F)_(3i)
|
|
$
|
|
))
|
|
|
|
== Solution
|
|
|
|
Since every third number is even, take each third element of the sequence until four million. Three step jumps can be taken as defined by the matrix above.
|
|
|
|
```py
|
|
>>> class Pair:
|
|
... def __init__(self, fi_m1, fi):
|
|
... self.fi_m1 = fi_m1
|
|
... self.fi = fi
|
|
>>> def f_3(pair):
|
|
... return Pair(
|
|
... pair.fi_m1 + (2 * pair.fi),
|
|
... (2 * pair.fi_m1) + (3 * pair.fi)
|
|
... )
|
|
>>> x = Pair(1, 2)
|
|
>>> s = 0
|
|
>>> while x.fi < 4e6:
|
|
... s += x.fi
|
|
... x = f_3(x)
|
|
>>> print(s)
|
|
4613732
|
|
``` |