def triangle(num):
if num == 1:
return num
return num + triangle(num - 1)
Your function triangle(num) is a recursive way to calculate the triangular number — the sum of all integers from 1 up to num.
How it works
Base case: If
num == 1, it returns 1.Recursive case: Otherwise, it returns
num + triangle(num - 1), which keeps calling itself until it reaches 1.
So for triangle(4):
4 + triangle(3)4 + (3 + triangle(2))4 + (3 + (2 + triangle(1)))4 + 3 + 2 + 1 = 10
Key points
It computes the sum .
This is known as the n-th triangular number.
Formula:
def square(num):
return triangle(num-1) + triangle(num)
Explanation
triangle(n)gives the sum of integers from 1 ton. Example:triangle(4) = 1+2+3+4 = 10.In your
square(num)function, you’re adding:triangle(num-1)→ sum of numbers up tonum-1triangle(num)→ sum of numbers up tonum