1

Ruby 新手,并试图找到一个 3 位数字“abc”:

for a in 0..9
    for b in 0..9
        for c in 0..9
            if a*a+b*b+c*c == (100*a+10*b+c)/11.0
                puts "#{a}#{b}#{c}"
            end
        end
    end
end

这太冗长了,有什么方法可以优化它,或者用另一种“ruby”方式编写它?

4

2 回答 2

3

解决方案来自:Wolfram Alpha :)

这是另一个有趣的解决方案。不是真的更快,只是更紧凑,如果你正在寻找的话,可能更像红宝石:

(0..9).to_a.repeated_permutation(3).select { |a,b,c| 
  a*a+b*b+c*c == (100*a+10*b+c)/11.0 
}
=> [[0, 0, 0], [5, 5, 0], [8, 0, 3]]
于 2012-06-30T20:06:29.933 回答
2

This is equivalent to finding a,b,c such that

100*a + 10*b + c = 11 * (a*a + b*b +c*c)

i.e. 100*a + 10*b + c must be divisible by 11. Simple number theory tells you that when a,b,c are digits, this means that

`a + c - b`

must be a multiple of 11 so

`a + c = b or a + c = 11 +b`

So for a given values of a and b you only need to check two values of c : b -a and 11 +b -a rather than 10. You can cut the search space in two again: if a > b you only need to check the latter of those two values and if a <= b you need only check the former.

Thus instead of checking 1000 triplets of numbers you should only need to check 100, which should be 10 times faster.

for a in 0..9
  for b in 0..9
    if a > b
      c = 11 +b -a
    else
      c = b - a
    end
    if a*a+b*b+c*c == (100*a+10*b+c)/11.0
      puts "#{a}#{b}#{c}"
    end
  end
end
于 2012-06-30T21:45:41.603 回答