Added 24 and 25 to ipython.

This commit is contained in:
2018-02-06 22:22:00 +01:00
parent b7e7314e99
commit ee6e6e6445
8 changed files with 948 additions and 7 deletions

View File

@@ -15,14 +15,100 @@
"Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We reuse the sum of proper divisors function and use it to tell whether a number is abundant or not."
]
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 20,
"metadata": {
"collapsed": true
"collapsed": false
},
"outputs": [],
"source": []
"source": [
"def sum_of_proper_divisors(n):\n",
" from math import sqrt\n",
" if n == 1:\n",
" return 0\n",
" s = 1\n",
" for i in range(2, int(sqrt(n)) + 1):\n",
" if n % i == 0:\n",
" s += i\n",
" x = (n // i)\n",
" if x != i:\n",
" s += x\n",
" return s\n",
"\n",
"def is_abundant(n):\n",
" return sum_of_proper_divisors(n) > n\n",
"\n",
"assert(is_abundant(7) == False)\n",
"assert(is_abundant(12) == True)\n",
"\n",
"abundant_numbers_smaller_30000 = [n for n in range(1, 30001) if is_abundant(n)]\n",
"abundant_numbers_smaller_30000_set = set(abundant_numbers_smaller_30000)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now that we have all abundant numbers in sorted order we can write a function which tests whether a number can be written as a sum of two abundant numbers."
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def is_sum_of_two_abundants(n):\n",
" for a in abundant_numbers_smaller_30000:\n",
" if a > (n // 2):\n",
" return False\n",
" r = n - a\n",
" if r in abundant_numbers_smaller_30000_set:\n",
" return True\n",
" return False\n",
"\n",
"assert(is_sum_of_two_abundants(24) == True)\n",
"assert(is_sum_of_two_abundants(23) == False)\n",
"assert(is_sum_of_two_abundants(28123) == True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we try to brute force."
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4179871\n"
]
}
],
"source": [
"s = sum([i for i in range(1, 30000) if not is_sum_of_two_abundants(i)])\n",
"print(s)\n",
"assert(s == 4179871)"
]
}
],
"metadata": {
@@ -46,7 +132,8 @@
},
"tags": [
"perfect number",
"abundant"
"abundant",
"factors"
]
},
"nbformat": 4,