KobbyAdarkwa
KobbyAdarkwa

Reputation: 181

Writing a sequence that adds the summation of Num: Ruby

How can I write an expression that adds numbers in a sequence to find the summation of num. Num is a positive integer for example:

summation(2) -> 3
1 + 2

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

This is what my code looks like currently:

#8(num)+1%2 = 4.5
#4.5* 8 = 36 
# num #=> 36 

def summation(num)
num= num*num +1 % 2 
end

and here is a link to the kata for reference.

Upvotes: 0

Views: 138

Answers (1)

Jörg W Mittag
Jörg W Mittag

Reputation: 369584

We can use the well-known closed-form formula for the triangular numbers: n * (n + 1) / 2

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

However, this formula is already implemented by Enumerable#sum for Ranges, so this would probably be more readable:

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

Upvotes: 4

Related Questions