Last active
December 15, 2015 08:19
-
-
Save kevincennis/5230057 to your computer and use it in GitHub Desktop.
Euler 21
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var max = 1e4, obj = {}, val = t = i = 0 | |
function sum( n ) { | |
for ( var m = Math.sqrt(n), v = 1, i = 2; i <= m; ++i ) | |
!(n % i) && (v += i) && i != m && (v += n / i) | |
return n ? v : 0 | |
} | |
for ( ; i < max; ++i ) | |
if ( !obj[i] && (t = sum(i)) != i && sum(t) == i ) | |
val += (obj[i] = obj[t] = i + t) | |
console.log(val) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
maximum = 10000 | |
lookup = [] | |
result = 0 | |
def getDivisors ( num ): | |
end = int( math.floor( math.sqrt(num) ) ) | |
val = 1 | |
for i in range (2, end): | |
if num % i == 0: | |
val = val + i | |
if i * i != num: | |
val = val + ( num / i ) | |
return val | |
for i in range (0, maximum): | |
if i in lookup: | |
continue | |
temp = getDivisors( i ) | |
if temp != i and getDivisors( temp ) == i: | |
lookup.append(temp) | |
lookup.append(i) | |
result = result + temp + i | |
print( result ) |
Better way to find divisors...
Kevins-MacBook-Pro-2:Euler kevin$ time node 21.js
31626
real 0m0.069s
user 0m0.059s
sys 0m0.008s
Kevins-MacBook-Pro-2:Euler kevin$ time python 21.py
31626
real 0m0.218s
user 0m0.210s
sys 0m0.007s
And some more optimizations:
Kevins-MacBook-Pro-2:Euler kevin$ time node 21.js
31626
real 0m0.062s
user 0m0.053s
sys 0m0.008s
Kevins-MacBook-Pro-2:Euler kevin$ time python 21.py
31626
real 0m0.155s
user 0m0.146s
sys 0m0.007s
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Kevins-MacBook-Pro-2:Euler kevin$ time node 21.js
31626
real 0m0.204s
user 0m0.193s
sys 0m0.010s
Kevins-MacBook-Pro-2:Euler kevin$ time python 21.py
31626
real 0m4.651s
user 0m4.639s
sys 0m0.010s