euler/ipython/EulerProblem057.ipynb

156 lines
3.4 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Square root convergents (Euler Problem 57)"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"[https://projecteuler.net/problem=57](https://projecteuler.net/problem=57)\n",
"\n",
"It is possible to show that the square root of two can be expressed as an infinite continued fraction.\n",
"\n",
"√ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...\n",
"\n",
"By expanding this for the first four iterations, we get:\n",
"\n",
"1 + 1/2 = 3/2 = 1.5\n",
"\n",
"1 + 1/(2 + 1/2) = 7/5 = 1.4\n",
"\n",
"1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...\n",
"\n",
"1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379...\n",
"\n",
"The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion, 1393/985, is the first example where the number of digits in the numerator exceeds the number of digits in the denominator.\n",
"\n",
"In the first one-thousand expansions, how many fractions contain a numerator with more digits than denominator?"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"def get_digit_count(n):\n",
" c = 0\n",
" while n:\n",
" c += 1\n",
" n //= 10\n",
" return c\n",
"\n",
"assert(get_digit_count(1337) == 4)"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": true
},
"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",
"assert(gcd(100, 35) == 5)\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)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"def next_expension(n, d):\n",
" n, d = add_fractions(1, 1, n, d)\n",
" return add_fractions(1, 1, d, n)\n",
"\n",
"c = 0\n",
"\n",
"n, d = (3, 2)\n",
"for i in range(1000):\n",
" if get_digit_count(n) > get_digit_count(d):\n",
" c += 1\n",
" n, d = next_expension(n, d)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"153\n"
]
}
],
"source": [
"s = c\n",
"print(s)\n",
"assert(s == 153)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"completion_date": "Mon, 24 Dec 2018, 23:35",
"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": [
"square root",
"gcd",
"airplane",
"fractions"
]
},
"nbformat": 4,
"nbformat_minor": 2
}