Yêu cầu:
– Nhập vào số nguyên dương n
– Tính tổng S(n) = 1^2 + 2^2 + … + n^2
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*i
test.py
""" # Author: VNCODING # Function: S(n) = 1^2 + 2^2 + ... + n^2 # 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*i print("S = ", S)
Kết quả:
Input N:
-3
Input N again:
0
Input N again:
9
S = 285
Leave a Reply
You must be logged in to post a comment.