euler/ipython/EulerProblem065.ipynb

117 lines
2.7 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Convergents of e (Euler Problem 65)\n",
"\n",
"Hence the sequence of the first ten convergents for √2 are:\n",
"\n",
"1, 3/2, 7/5, 17/12, 41/29, 99/70, 239/169, 577/408, 1393/985, 3363/2378, ...\n",
"\n",
"What is most surprising is that the important mathematical constant,\n",
"\n",
"e = [2; 1,2,1, 1,4,1, 1,6,1 , ... , 1,2k,1, ...].\n",
"\n",
"The first ten terms in the sequence of convergents for e are:\n",
"\n",
"2, 3, 8/3, 11/4, 19/7, 87/32, 106/39, 193/71, 1264/465, 1457/536, ...\n",
"\n",
"The sum of digits in the numerator of the 10th convergent is 1+4+5+7=17.\n",
"\n",
"Find the sum of digits in the numerator of the 100th convergent of the continued fraction for e."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"def gcd(a, b):\n",
" if b > a:\n",
" a, b = b, a\n",
" while a % b != 0:\n",
" a, b = b, a % b\n",
" return b\n",
"\n",
"def add_fractions(n1, d1, n2, d2):\n",
" d = d1 * d2\n",
" n1 = n1 * (d // d1)\n",
" n2 = n2 * (d // d2)\n",
" n = n1 + n2\n",
" p = gcd(n, d)\n",
" return (n // p, d // p)\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"272\n"
]
}
],
"source": [
"def next_expansion(previous_numerator, previous_denumerator, value):\n",
" if previous_numerator == 0:\n",
" return (value, 1)\n",
" return add_fractions(previous_denumerator, previous_numerator, value, 1)\n",
"\n",
"e_sequence = [2] + [n for i in range(2, 1000, 2) for n in (1, i, 1)]\n",
"\n",
"n, d = 0, 1\n",
"\n",
"for i in range(100, 0, -1):\n",
" n, d = next_expansion(n, d, e_sequence[i - 1])\n",
"\n",
"s = sum([int(l) for l in str(n)])\n",
"print(s)\n",
"assert(s == 272)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"completion_date": "Wed, 23 Jan 2019, 05:54",
"kernelspec": {
"display_name": "Python 3",
"language": "python3.6",
"name": "python3"
},
"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.6.5"
},
"tags": [
"expansion",
"e",
"sequence"
]
},
"nbformat": 4,
"nbformat_minor": 2
}