How to split a Number to Natural Numerals in Ruby -
for example:
input: 15
output:
15 = 1+2+3+4+5
15 = 4+5+6
15 = 7+8
input: 4
output: cannot split
here's 1 way:
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? 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
Comments
Post a Comment