{ "cells": [ { "cell_type": "markdown", "id": "1899e933", "metadata": {}, "source": [ "# Even Fibonacci Numbers\n", "> Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first terms will be:\n", "> $$1, 2, 3, 5, 8, 13, 21, 34, 55, 89, \\ldots$$\n", "> By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.\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" ] } ], "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 }