简体   繁体   中英

Ruby - Project Euler #23 Taking too long to run

I am quite new to ruby and just to get a hang of it, i tried to solve some project euler problems. The one i am currently stuck on is the #23 problem.

The link: http://projecteuler.net/problem=23

The problem is that the ruby solution keeps running and i was tired waiting.

The solution:

def check(n)
  s=0
  for i in (1..(n/2)+1)
    if n % i == 0 then
      s+=i
    end
  end

  if s>n then
    return true

  end
end

def abundant()
  sum = 0
  for j in (1..28123)
    for k in (1..28123)
      ans = check(j)
      ans2 = check(k)
      if ans == true and ans2 == true then
        sum += (j + k)
      end    

    end
  end
  return sum
end        

a = abundant()
puts a

Any help will be highly appreciated! Thanks!

OK. So i will do some caching later. But i made a few of my own attempts to lessen the looping.

This is the current code now:

def check(n)
  s=0
  for i in (1..(n/2)+1)
    if n % i == 0 then
      s+=i
    end
  end

  if s>n then
    return true
  else
    return false

  end
end

def abundant()
  sum = 0
  for j in (1..28123)
    ans = check(j)
    if ans == false then
      for k in (j..28123)
        ans2 = check(k)
        if ans2 == false then
          sum += (j+k)
        end

      end  
    end
  end
end  

a = abundant()
puts a

You should try caching your results - if you already calculated if 13453 is a prime, you don't have to check it again:

@cache = {}
def check(n)
  if @cache[n].nil?
    s=0
    for i in (1..(n/2)+1)
      if n % i == 0 then
        s+=i
      end
    end

    @cache[n] = s>n
  end
  @cache[n]
end

def abundant()
  sum = 0
  for j in (1..28123)
    for k in (1..28123)
      ans = check(j)
      ans2 = check(k)
      if ans == true and ans2 == true then
        sum += (j + k)
      end    

    end
  end
  return sum
end        

a = abundant()
puts a

What this does is save every result (whether a number is a prime or not) in a Hashtable , and before making the calculation, it first checks if the result is already in the Hashtable of saved numbers. That is what caching means.

If you read your code, you'll see that you calculate whether each number is a prime 28124(!) times (once for each iteration in the inner loop, plus one when j==k ), this many times, and for a heavy calculation as well... the fact that you re-calculate each number for so many times makes you code a few orders of magnitude slower than when caching the results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM