例如:
输入: 15
输出:
15 = 1+2+3+4+5
15 = 4+5+6
15 = 7+8
输入: 4
输出:无法拆分
这是一种方法:
def natural_numerals(value)
results = []
(1..value-1).each {|i| (i..value-1).each {|j| results << (i..j).to_a.join("+") if (i+j)*(j-i+1)/2 == value}}
if results.empty? then nil else results end
end
output1 = natural_numerals(15)
output2 = natural_numerals(4)
puts output1.inspect #=> ["1+2+3+4+5", "4+5+6", "7+8"]
puts output2.inspect #=> nil