ruby - All possible products -


i'm trying find possible product of 2 3-digit numbers. when work small ranges, i'm able output in short amount of time when ranges big, seems take long time. there way to shorten time result?

the problem i'm working on is:

"a palindromic number reads same both ways. largest palindrome made product of 2 2-digit numbers 9009 = 91 × 99.

find largest palindrome made product of 2 3-digit numbers."

a = [] x in 100..999     y in 100..999         num = (x * y)         unless a.include? num             a.push num         end     end end  p 

looking @ code quick optimization can make use set rather array store computed products.

since a array, a.include?(num) have iterate through entire list of elements before returning true / false.

if a set, a.include?(num) return in sub linear time.

example:

require 'set' = set.new x in 100..999     y in 100..999         num = (x * y)         unless a.include? num           a.add(num)         end     end end puts a.to_a.join(", ") 

moreover 1 of nice properties of set stores unique elements following equivalent:

require 'set' = set.new x in 100..999     y in 100..999         num = (x * y)         a.add(num)     end end puts a.to_a.join(", ") 

Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

visual studio 2010 - Connect to informix database windows form application -

android - Associate same looper with different threads -