Created
July 20, 2013 21:22
-
-
Save elreimundo/6046468 to your computer and use it in GitHub Desktop.
I wrote this to solve another Project Euler problem (the number of divisors for a given triangular number). To find the number of divisors that a number has, the quickest way is to take the prime factorization of the number. Next, add one to each of the exponents of the prime factors, and find the product of these new exponents. There's your num…
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
whichtrinum = 1 | |
while true | |
trinum = (whichtrinum * (whichtrinum + 1)) / 2 | |
numtofactor = trinum | |
factors = [] | |
factor = 2 | |
while numtofactor != 1 | |
if numtofactor % factor == 0 | |
factors << factor | |
numtofactor = numtofactor / factor | |
factor = 2 | |
elsif factor > Math.sqrt(numtofactor) | |
factors << numtofactor | |
numtofactor = 1 | |
factor = 2 | |
else | |
factor.even? ? factor += 1 : factor += 2 | |
end | |
end | |
divisors = 1 | |
factors.uniq.each { |base| divisors *= (factors.count(base) + 1) } | |
if divisors > 500 | |
break | |
end | |
whichtrinum += 1 | |
end | |
puts trinum |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Might have been even more efficient to find the divisors of whichtrinum and (whichtrinum + 1)/2 (or the reverse, depending on which is even) and then multiply together the number of divisors of each... Oh, well, live and learn.