Largest palindrome product - Ruby

Asked

Viewed 68 times

0

How to make this code faster? It works, but not fast enough.

#!/bin/ruby

def isPalin(mul)
  if mul.to_s == mul.to_s.reverse then
    return true
  else
    return false
  end
end

def lp(n)
  arr = []

  for a1 in (100..999)
    for a2 in (100..999)
      mul = a1*a2
      break if mul > n
      if mul <= n then
        arr.push(mul) if isPalin(mul)
      end
    end
  end

  arr.sort!
  puts arr[arr.length-1]

end


t = gets.strip.to_i
for a0 in (0..t-1)
  n = gets.strip.to_i

  lp(n)
end

Thanks for your help!

  • 1

    Please translate your question, this is the English OS.

  • translated right below, Sorry!

  • Enrique, the field below is for answers only, the correct is you edit the question with the translation.

1 answer

0

The double loop for does folded work: n1 * N2 == N2 * n1. Use the outside index in the inside loop to prevent repetition.

(100..999).each do |n1| (n1..999).each do |n2| mul = n1 * n2 if mul <= n arr << mul if palindromo?(mul.to_s) else break end end end

each is an Enumerable method, inherited by Array. See documentation.

The isPalin function can be made simpler, starting by cutting the if ... then true else false:

def isPalin(mul) return mul.to_s == mul.to_s.reverse end

Until the return end can be cut, leaving only the expression, because the function will return the last calculated value.

If you assume that the value is already a string, you can use the fact that strings have their characters indexed, and admit negative indexes:

def palindromo?(s) tam = s.size return true if tam < 2 return (0..(tam/2)).all? { |i| s[i] == s[tam - i - 1] } end

all? is another method of Enumerable: returns true if all elements of the enumerable return true when applied to the block.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.