BÀI TẬP KỸ THUẬT LẬP TRÌNH (Python)

Bài tập Python - Chương 1

Bài tập Python - Chương 1

Bài 1: Tính S(n) = 1 + 2 + 3 + ... + n

def sum_n(n):
    return sum(range(1, n + 1))

n = int(input("Nhập n: "))
print("Tổng S(n) =", sum_n(n))

Bài 2: Tính S(n) = 1^2 + 2^2 + ... + n^2

def sum_squares(n):
    return sum(i**2 for i in range(1, n + 1))

n = int(input("Nhập n: "))
print("Tổng S(n) =", sum_squares(n))

Bài 3: Tính S(n) = 1 + ½ + 1/3 + ... + 1/n

def harmonic_sum(n):
    return sum(1/i for i in range(1, n + 1))

n = int(input("Nhập n: "))
print("Tổng S(n) =", harmonic_sum(n))

Bài 4: Tính S(n) = ½ + ¼ + ... + 1/2n

def half_harmonic_sum(n):
    return sum(1/(2 * i) for i in range(1, n + 1))

n = int(input("Nhập n: "))
print("Tổng S(n) =", half_harmonic_sum(n))

Bài 5: Tính S(n) = 1 + 1/3 + 1/5 + ... + 1/(2n + 1)

def odd_reciprocal_sum(n):
    return sum(1/(2 * i + 1) for i in range(n))

n = int(input("Nhập n: "))
print("Tổng S(n) =", odd_reciprocal_sum(n))

Bài 6: Tính S(n) = 1/(1x2) + 1/(2x3) + ... + 1/(n x (n + 1))

def fraction_sum(n):
    return sum(1/(i * (i + 1)) for i in range(1, n + 1))

n = int(input("Nhập n: "))
print("Tổng S(n) =", fraction_sum(n))

Bài 7: Tính S(n) = ½ + 2/3 + ¾ + ... + n / (n + 1)

def fraction_increment_sum(n):
    return sum(i/(i + 1) for i in range(1, n + 1))

n = int(input("Nhập n: "))
print("Tổng S(n) =", fraction_increment_sum(n))

Bài 76: Kiểm tra số nguyên 4 byte có dạng 3^k hay không

def is_power_of_3(n):
    if n <= 0:
        return False
    while n % 3 == 0:
        n //= 3
    return n == 1

n = int(input("Nhập n: "))
if is_power_of_3(n):
    print(f"{n} là lũy thừa của 3.")
else:
    print(f"{n} không phải là lũy thừa của 3.")

Đăng nhận xét

Mới hơn Cũ hơn