Home > katas > Grasshopper - Summation (8kyu) [Ruby]

Grasshopper - Summation (8kyu) [Ruby]


Chek kata on Codewars

Description:

Write a program that finds the summation of every number from 1 to num. The number will always be a positive integer greater than 0.

For example:

summation(2) -> 3
1 + 2

summation(8) -> 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8

Solution 1

Let's start with loop solutions.

def summation(num)
  sum = 0
  num.times do |n|
      sum += n+1
  end
  sum
end

Solution 2

Let's solve it with Gauss Formula.

def summation(num)
  num * (num + 1) / 2
end

Solution 3

Let's solve it with reduce.

def summation(num)
  (1..num).reduce(0, :+)
end

Let's solve it with inject.

def summation(num)
  (1..num).inject { |acc, cur| acc + cur }
end

Solution 4

Let's solve it with sum.

def summation(num)
  (1..num).sum
end

Solution 5

Let's solve it with recursion.

def summation(num)
  num != 0 ? num + summation(num - 1) : num
end
© 2021, Andrew Losseff