Skip to content

Instantly share code, notes, and snippets.

@elreimundo
Created July 20, 2013 21:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elreimundo/6046468 to your computer and use it in GitHub Desktop.
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…
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
@elreimundo
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment