...

/

Solution: Consecutive Sums

Solution: Consecutive Sums

Go over the implementation of finding consecutive numbers that sum a target number.

We'll cover the following...

Solution

print "Enter a number: "
input = gets.chomp.to_i
y = (input + 1) / 2

(1..y - 1).each do |starting_number|

  (starting_number..y).each do |j|
    sum = (starting_number..j).to_a.inject(0){ |sum, item| sum + item }
    if sum == input
      puts "#{input} = #{(starting_number..j).to_a.join(' + ')}"
      break
    end
  end
  
end
Finding consecutive numbers that sum to a target number

Explanation

  • Line 9: Here, starting_number is the outer loop variable defined on line 6, and j is the inner loop variable defined on line 8.

  • Let’s dry run it for input equal to 99, and y equal to 9+12 ...