CS 61A

Structure and Interpretation of Computer Programs, Spring 2015

Instructor: John DeNero




Question | Triangular Sum

Define triangular_sum, which takes an integer n and returns the sum of the first n triangle integer, while printing each of the triangle numbers between 1 and the nth triangle number.

The forumula for the nth Triangular number is:

(n + 1) * n / 2

def triangular_sum(n):
    """
    >>> t_sum = triangular_sum(5):
    1.0
    3.0
    6.0
    10.0
    15.0
    >>> t_sum
    35.0
    """
    ## YOUR CODE HERE ##
def triangular_sum(n):
    count = 1
    t_sum = 0
    while count <= n:
        t_number = count * (count + 1) / 2
        print(t_number)
        t_sum += t_number
        count += 1
    return t_sum