Số mạnh (Strong number) là số mà tổng giai thừa các chữ số bằng số n. Giai thừa: tích các số từ 1 đến số đó, ký hiệu ! (Ví dụ: 5! = 5x4x3x2x1 = 120). Kiểm tra số strong, dùng toán tử dư/modulus và vòng lặp 'while'.
Minh họa:
Ví dụ
my_sum=0
my_num = 296
print("The number is")
print(my_num)
temp = my_num
while(my_num):
i=1
fact=1
remainder = my_num%10
while(i<=remainder):
fact=fact*i
i=i+1
my_sum = my_sum+fact
my_num=my_num//10
if(my_sum == temp):
print("The number is a strong number")
else:
print("The number is not a strong number")
Kết quả
The number is 296 The number is not a strong number
Giải thích
- Khởi tạo sum = 0.
- Định nghĩa số, hiển thị console.
- Gán số cho biến tạm.
- While loop xác định remainder.
- While loop lặp xem iterator <= remainder.
- Nếu nhỏ hơn, 'fact' nhân iterator.
- Tăng 1.
- Cộng sum với 'fact'.
- Nếu 'temp' = sum, là strong number.