Python – Tính tổng S(n) = 1+2+3+4+ … +n

Yêu cầu:
– Nhập vào số nguyên dương n
– Tính tổng s(n) = 1 + 2 + 3 + 4 + … + n

Giải thuật:
– Dùng vòng lặp for, do while để duyệt biến i từ 1 tới n
– Tính tổng: s = s + i

test.py

"""
# Author: VNCODING
# Function: s(n) = 1 + 2 + 3 + 4 + ... + n
# 2022/08/17        first create    VNCODING
"""
print("Input N: ")
N = input()

while int(N) < 1:
    print("Input N again: ")
    N = input()

S = 0
for i in range(1, int(N)+1):
    S += i

print("S = ", S)

Kết quả:
Input N:
10
S = 55

Be the first to comment

Leave a Reply