Wrote a fast solution for 3 in ipython.

This commit is contained in:
2018-02-02 11:19:49 +01:00
parent 1da214e4e9
commit 53b662c3a8

View File

@@ -21,9 +21,7 @@
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"metadata": {},
"outputs": [],
"source": [
"def get_primes_smaller(number):\n",
@@ -49,9 +47,7 @@
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"metadata": {},
"outputs": [],
"source": [
"import math\n",
@@ -85,10 +81,8 @@
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
@@ -103,7 +97,8 @@
" return get_prime_factors(number)[-1]\n",
"\n",
"assert(get_largest_prime(13195) == 29)\n",
"print(get_largest_prime(600851475143))"
"#print(get_largest_prime(600851475143))\n",
"print(6857) # computed the previously but remove it so that we can reexecute the complete kernel"
]
},
{
@@ -117,12 +112,59 @@
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"6857\n"
]
}
],
"source": [
"def is_prime(n, smaller_primes):\n",
" for s in smaller_primes:\n",
" if n % s == 0:\n",
" return False\n",
" if s * s > n:\n",
" return True\n",
" return True\n",
"\n",
"def prime_generator_function():\n",
" primes = [2, 3, 5, 7]\n",
" for p in primes:\n",
" yield p\n",
" while True:\n",
" p += 2\n",
" if is_prime(p, primes):\n",
" primes.append(p)\n",
" yield p\n",
" \n",
"def get_prime_factors(number):\n",
" prime_generator = prime_generator_function()\n",
" remainder = number\n",
" factors = []\n",
" for p in prime_generator:\n",
" while remainder % p == 0:\n",
" remainder /= p\n",
" factors.append(p)\n",
" if remainder == 1 or p * p > number:\n",
" break\n",
" if remainder != 1:\n",
" factors.append(remainder)\n",
" return factors\n",
"\n",
"print(get_largest_prime(600851475143))\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here we go. Obviously much better than precalculation primes that we never need."
]
}
],
"metadata": {
@@ -141,9 +183,9 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.4"
"version": "3.6.3"
}
},
"nbformat": 4,
"nbformat_minor": 0
"nbformat_minor": 1
}