Solution: Consecutive Sums
Explore how to use Ruby loops and control flow to find consecutive sums that equal a given number. Understand the role of inner and outer loops, and learn to optimize your code with break statements to avoid unnecessary iterations.
We'll cover the following...
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_numberis the outer loop variable defined on line 6, andjis the inner loop variable defined on line 8.Let’s dry run it for
inputequal to, and yequal to...