Nick Dubus
Nick Dubus

Reputation: 91

Ruby project Euler #12 efficiency

I'm attempting to do problem #12 on project euler (see quote below)

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?

I have written out what I "think" is a valid solution in Ruby, however the runtime is incredibly slow. See code below:

    def num_divisors_of(num)
  sum = 0
  for i in 1..num/2 do
    if num % i == 0 then sum += 1 end
  end
  return sum += 1
end

currentSum = 0

for i in 1..10000 do
  currentSum += i
   if num_divisors_of(currentSum) > 500
     puts currentSum
   break
   end
end

Basically, I start at 1, add it to a running total, and check the number of divisors of that total. If the number is over 500, I stop and return the number.

I'm wondering if there's another way to look at this that I haven't thought of yet? I've thought of finding prime factors (I'm pretty sure my method to find the number of divisors of a number is what's bogging me down), but otherwise I really have no clue where to make it more efficient.

Any thoughts/ideas?

EDIT: Okay, I found a way to save some runtime. When searching for divisors, I look up until the square root of the number, and add 2 every time I find a divisor (ex: lets say for divisors of 625, I find 5. 5 * 125 = 625, so those are 2 divisors). Next, if the square root IS an exact divisor, then remove 1 (as I'll have counted it twice. For example, 25 * 25 = 625, but thats just 1 divisor).

Really sped up my runtime, and I got the answer. Woohoo!

Upvotes: 0

Views: 487

Answers (1)

hbejgel
hbejgel

Reputation: 4837

Look at this answer: All factors of a given number

Then you just count the number of elements in the array until you find one with more than 500 divisors.

Upvotes: 1

Related Questions