eulerbooks/notebooks/problem0002.ipynb

96 lines
2.3 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"id": "1899e933",
"metadata": {},
"source": [
"# [Even Fibonacci Numbers](https://projecteuler.net/problem=2)\n",
"\n",
"There's a lot to learn about the [Fibonacci numbers](https://en.wikipedia.org/wiki/Fibonacci_sequence), and this will not be the last time we see them in a Project Euler problem, but for now this problem keeps it relatively simple.\n",
"\n",
"Since this is a SageMath notebook, we'll use its functionality so we can keep our code simple like the problem."
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "57b68465",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"4613732"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sum(n for n in fibonacci_xrange(1, 4000000) if n % 2 == 0)"
]
},
{
"cell_type": "markdown",
"id": "eef788da",
"metadata": {},
"source": [
"Even without SageMath, it's easy to implement our own generator of the sequence up to $n$."
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "24a7c257",
"metadata": {},
"outputs": [],
"source": [
"def fib(n):\n",
" a = 0\n",
" b = 1\n",
" while a <= n:\n",
" yield a\n",
" a, b = b, a + b"
]
},
{
"cell_type": "markdown",
"id": "b3293a7d",
"metadata": {},
"source": [
"## Relevant sequences\n",
"* Fibonacci numbers: [A000045](https://oeis.org/A000045)\n",
"* Partial sums of even Fibonacci numbers: [A099919](https://oeis.org/A099919)\n",
"\n",
"#### Copyright (C) 2025 filifa\n",
"\n",
"This work is licensed under the [Creative Commons Attribution-ShareAlike 4.0 International license](https://creativecommons.org/licenses/by-sa/4.0/) and the [BSD Zero Clause license](https://spdx.org/licenses/0BSD.html)."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "SageMath 9.5",
"language": "sage",
"name": "sagemath"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.2"
}
},
"nbformat": 4,
"nbformat_minor": 5
}