Python Program to Generate Triangular Numbers in an Interval


This python program generates triangular numbers in an interval given by user.

Triangular Numbers are those numbers which are obtained by continued summation of the natural numbers 1, 2, 3, 4, 5, etc.

Triangular Number Example: 15 is Triangular Number because it can be obtained by 1+2+3+4+5+6 i.e. 1+2+3+4+5+6=15

Also try: Check Triangular Number Online & Generate Triangular Numbers Online

Python Source Code: Generate Triangular Numbers


# Generate Perfect numbers in interval

# Function to check Triangular
def is_triangular(n):

    if n< 0:
        return False
    
    if n==0 or n==1:
        return True
    
    triangular_sum = 0

    for i in range(n):
        triangular_sum += i

        if triangular_sum == n:
            return True

        if i == n:
            return False

# Reading interval from user
min_value = int(input('Enter minimum value: '))
max_value = int(input('Enter maximum value: '))

# Looping & displaying if it is Triangular
# Here min_vale & max_value are included
print('Triangular numbers from %d to %d are:' %(min_value, max_value))
for i in range(min_value, max_value+1):
    if is_triangular(i):
        print(i, end=' ')

Triangular Number Generation: Output

Enter minimum value: -100
Enter maximum value: 1000
Triangular numbers from -100 to 1000 are:
0 1 3 6 10 15 21 28 36 45 55 66 78 91 105 120 136 153 171 190 210 231 253 276 300 325 351 378 406 435 465 496 528 561 595 630 666 703 741 780 820 861 903 946 990

Triangular Number Generation: Code Output

We first read min_value and max_value from user. Function is_triangular() is used to check whether a given number is Triangular or not. We loop from min_value to max_value and pass each number to is_triangular() function. If this function returns True, then we print it.