对回文产品问题感到困惑 [英] Puzzled over palindromic product problem

查看:94
本文介绍了对回文产品问题感到困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在学习Ruby,所以我想尝试一些Euler拼图项目.令人尴尬的是,我只解决了问题4 ...

I've been learning Ruby, so I thought I'd try my hand at some of the project Euler puzzles. Embarrassingly, I only made it to problem 4...

问题4如下:

回文数读相同 双向.产生的最大回文 从两个两位数的乘积 数字是9009 = 91×99.

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

找到由以下材料制成的最大回文 两个3位数的乘积.

Find the largest palindrome made from the product of two 3-digit numbers.

所以我想我会在嵌套的for循环中从999循环到100,并对回文进行测试,然后在发现第一个(应该是最大的)循环时退出循环:

So I figured I would loop down from 999 to 100 in a nested for loop and do a test for the palindrome and then break out of the loops when I found the first one (which should be the largest one):

final=nil
range = 100...1000
for a in range.to_a.reverse do
  for b in range.to_a.reverse do
    c=a*b
    final=c if c.to_s == c.to_s.reverse
    break if !final.nil?
  end
  break if !final.nil?
end
puts final

这确实会输出回文580085,但显然这不是该范围内两个三位数字的最高乘积.奇怪的是,如示例中所示,如果我将范围更改为10 ... 100,则相同的代码成功返回9009.

This does output a palindrome 580085, but apparently this isn't the highest product of two three-digit numbers within the range. Strangely, the same code succeeds to return 9009, like in the example, if I change the range to 10...100.

  • 有人可以告诉我我要去哪里 错误吗?
  • 此外,还有更好的方法吗 打破内部循环?
  • Can someone tell me where I am going wrong?
  • Also, is there a nicer way to break out of the internal loop?

谢谢

推荐答案

您正在测试999 *(999 ... 100),然后是998 *(999 ... 100)

You are testing 999* (999...100), then 998 * (999...100)

因此,在测试997 * 996之前,您将测试999 * 500.

Hence you will be testing 999 * 500 before you test 997 * 996.

那么,您如何找到正确的电话号码?

So, how you we find that right number?

首先请注意,乘法是反射性的,a * b == b * a,因此b不必每次都从999 ... 0开始,只需a ... 0.

First note the multiplication is reflective, a * b == b * a, so b need not go from 999...0 every time, just a ...0.

当您找到一个palindrone时,将这两个因素加在一起并保存总和(也要保存这两个因素)

When you find a palindrone, add the two factors together and save the sum (save the two factors also)

在循环内部,如果(a + b)小于保存的总和,则放弃内部循环并移至下一个a.当跌落到sum/2以下时,您找不到的任何未来值都不会高于已经找到的值,所以您就完成了.

Inside the loop, if (a+b) is ever less than the saved sum, abandon the inner loop and move to the next a. When a falls below sum/2, no future value you could find would be higher than the one you've already found, so you're done.

这篇关于对回文产品问题感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆