Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of all numbers

Tags:

python

I need to write a function that calculates the sum of all numbers n.

Row 1:          1 
Row 2:         2 3 
Row 3:        4 5 6 
Row 4:       7 8 9 10 
Row 5:     11 12 13 14 15 
Row 6:   16 17 18 19 20 21 

It helps to imagine the above rows as a 'number triangle.' The function should take a number, n, which denotes how many numbers as well as which row to use. Row 5's sum is 65. How would I get my function to do this computation for any n-value?

For clarity's sake, this is not homework. It was on a recent midterm and needless to say, I was stumped.

like image 594
trainreq Avatar asked Oct 11 '12 17:10

trainreq


People also ask

What is the sum of all numbers called?

In mathematics, summation is the addition of a sequence of any kind of numbers, called addends or summands; the result is their sum or total.

How do you find the sum of all numbers?

The formula to calculate the sum of integers is given as, S = n(a + l)/2, where, S is sum of the consecutive integers n is number of integers, a is first term and l is last term.

Is Ramanujan summation correct?

Although the Ramanujan summation of a divergent series is not a sum in the traditional sense, it has properties that make it mathematically useful in the study of divergent infinite series, for which conventional summation is undefined.

What is the sum of 1 to 100 numbers?

Natural numbers are counting numbers only starting from 1. The sum of natural numbers 1 to 100 is 5050.


1 Answers

The leftmost number in column 5 is 11 = (4+3+2+1)+1 which is sum(range(5))+1. This is generally true for any n.

So:

def triangle_sum(n):
    start = sum(range(n))+1
    return sum(range(start,start+n))

As noted by a bunch of people, you can express sum(range(n)) analytically as n*(n-1)//2 so this could be done even slightly more elegantly by:

def triangle_sum(n):
    start = n*(n-1)//2+1
    return sum(range(start,start+n))
like image 191
mgilson Avatar answered Oct 01 '22 19:10

mgilson