搜尋此網誌

2026年9月3日星期四

quiz

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 1+2++n.

  • This is known as the n-th triangular number.

  • Formula: n(n+1)2

小學奧數口訣︰頭項加尾項乘項數除二

def square(num):

    return triangle(num-1) + triangle(num)


Explanation

  • triangle(n) gives the sum of integers from 1 to n. Example: triangle(4) = 1+2+3+4 = 10.

  • In your square(num) function, you’re adding:

    • triangle(num-1) → sum of numbers up to num-1

    • triangle(num) → sum of numbers up to num

If num = 4
square(4) = 16
triangle(3) + tringle(4) = 6 + 10 = 16


Microsoft Copilot

沒有留言:

發佈留言