(Python) The triangular numbers is the number sequence 0, 1, 3, 6, 10, 15, 21, 2
ID: 3868393 • Letter: #
Question
(Python) The triangular numbers is the number sequence 0, 1, 3, 6, 10, 15, 21, 28, … The n:th triangular number is defined as the sum of the numbers from 0 to n, inclusive, that is, 0 + 1 + … + n. Note that the sequence starts from zero: The zeroth triangular number is zero, and the first triangular number is 1. There is also closed-form formula for the n:th triangular number: T(n) = n (n + 1) / 2. Your task is to write a function triangular(n) that computes and returns the n:th triangular number for any non-negative integer value n. The function must take one argument (that is, have one parameter), which is the value of n, and it must return an integer value (a value of type int).
Explanation / Answer
def triangular(n):
for i in range(0, n+1):
print(" n = {0}, triangular sequence = {1}".format(i, (i ** 2 +i)//2))
n = int(raw_input(" Enter an Integer:"))
triangular(n)
OUTPUT
Enter an Integer:10
n = 0, triangular sequence = 0
n = 1, triangular sequence = 1
n = 2, triangular sequence = 3
n = 3, triangular sequence = 6
n = 4, triangular sequence = 10
n = 5, triangular sequence = 15
n = 6, triangular sequence = 21
n = 7, triangular sequence = 28
n = 8, triangular sequence = 36
n = 9, triangular sequence = 45
n = 10, triangular sequence = 55
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.