Ruby方法返回意外值
我有一个方法,返回由两个小于_的3位数字的乘积生成的最大回文。它应该尽可能快地运行 回文数字的两种读取方式相同。由两个3位数字组成的最小回文是101101,它是143*707的乘积 这是我的代码:Ruby方法返回意外值,ruby,algorithm,Ruby,Algorithm,我有一个方法,返回由两个小于_的3位数字的乘积生成的最大回文。它应该尽可能快地运行 回文数字的两种读取方式相同。由两个3位数字组成的最小回文是101101,它是143*707的乘积 这是我的代码: def palindrome(smaller_than) max = 0 999.downto(143).each do |x| 999.downto(707).each do |y| break if (max > x * y) || (smaller_than
def palindrome(smaller_than)
max = 0
999.downto(143).each do |x|
999.downto(707).each do |y|
break if (max > x * y) || (smaller_than < x * y)
max = x * y if x * y == (x * y).to_s.reverse.to_i
end
end
return max
end
t = Time.now
puts palindrome(800000)
puts "Took #{Time.now-t}"
…它给了我正确的值793397
第二种方法有效,但速度太慢。为什么更快的first方法返回错误的值?您的第一个版本的问题是,它在不应该的地方中断了内部循环。这是一个工作版本,几乎和非工作版本一样快
def palindrome2(smaller_than)
max = 0
999.downto(143).each do |x|
999.downto(707).each do |y|
product = x * y
break if max > product
next if smaller_than < product
max = product if product.to_s == product.to_s.reverse
end
end
return max
end
如果不需要正常工作,任何程序都可以非常快地生成:
def palindrome2(smaller_than)
max = 0
999.downto(143).each do |x|
999.downto(707).each do |y|
product = x * y
break if max > product
next if smaller_than < product
max = product if product.to_s == product.to_s.reverse
end
end
return max
end
# max = x * y if (x * y == (x * y).to_s.reverse.to_i) && (smaller_than > x * y)
max = x * y if (smaller_than > x * y) && (x * y == (x * y).to_s.reverse.to_i)