Skip to content

Instantly share code, notes, and snippets.

@raywu
Created October 17, 2012 03:20
Show Gist options
  • Save raywu/3903524 to your computer and use it in GitHub Desktop.
Save raywu/3903524 to your computer and use it in GitHub Desktop.
Attempt to re-write the code
#Problem 12:
# The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
# Let us list the factors of the first seven triangle numbers:
# 1: 1
# 3: 1,3
# 6: 1,2,3,6
# 10: 1,2,5,10
# 15: 1,3,5,15
# 21: 1,3,7,21
# 28: 1,2,4,7,14,28
# We can see that 28 is the first triangle number to have over five divisors.
# What is the value of the first triangle number to have over five hundred divisors?
def compute(n)
$triagnum = []
# $factor = []
for x in (1..n)
$triagnum << (1..x).inject(0, :+)
end
$triagnum.each do |x|
n = 0
(1..x).each do |y|
if x % y == 0
n += 1
end
end
p "Triangle Number #{x} has #{n} divisors"
break if n >= 500
end
end
# First attempt to try and find the answer
#
# for x in $triagnum
# factor = []
# (1..x).each do |y|
# if x % y == 0
# factor << y
# end
# end
# $factor << [x, factor]
# end
# p "The triangle number #{$factor.last[0]} has #{$factor.last[1].count} divisors"
#
# n = 500
# for x in (400..n)
# compute x
# break if $factor.last[1].count >= 500
# n += 1
# end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment