Jack Kelly - 1 year ago 174

Ruby Question

The question:

Calculate the row sums of this triangle from the row index.

`row_sum_odd_numbers(1); # 1`

row_sum_odd_numbers(2); # 3 + 5 = 8

row_sum_odd_numbers(3); # 7 + 9 + 11 = 27

...

`Test.assert_equals(row_sum_odd_numbers(1), 1)`

Test.assert_equals(row_sum_odd_numbers(2), 8)

Test.assert_equals(row_sum_odd_numbers(13), 2197)

Test.assert_equals(row_sum_odd_numbers(19), 6859)

Test.assert_equals(row_sum_odd_numbers(41), 68921)

The solution to the question is as follows:

`def row_sum_odd_numbers(n)`

return n**3

end

I understand that this code returns the answer. I don't understand how it returns the answer. Why does the 3rd exponent of n return the row sum of odd numbers?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

It's just math calculation:)

lets find out what is the first summand:
before first summand we have `1 + 2 + 3 + ... + n-1`

odd numbers, their amount is `((n-1)*n)/2`

. So, first summand after them is

`((n-1)*n)/2 * 2 + 1 = (n-1)*n + 1`

.

Now we should just calculate our sum:
`row_sum_odd_numbers(n)= (n-1)*n + 1 + (n-1)*n + 3 + (n-1)*n + 5 +...+ (n-1)*n + 2*n - 1 =`

`(n-1)*n*n + 1 + 3 + 5 + ... + 2*n -1 = n^3 - n^2 + n^2 = n^3`

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**