一個整數被稱為 n 階的阿姆斯特朗數。當它的每一個數字被分開,立方,並加在一起,那麼它將導致一個和這個數相同的和,(即 pqrs…= pn+qn+rn+sn+…).
如果有一個三位數的阿姆斯特朗數,則每個數中的立方體總數等於該數本身。
示例:
371 = 3 * 3 * 3 + 7 * 7 * 7 + 1 * 1 * 1
= 27 + 343 + 1
= 371
Therefore, 371 is an Armstrong number.
在本教程中,我們將學習如何使用 Python 語言在兩個給定的整數之間找到阿姆斯特朗數。
例如:
Input: Two Integer Numbers: 1000 10000
Output: Armstrong Numbers Between Two Given Integers: 1634 8208 9474
Explanation: For the Output numbers: 1000 and 10000 are given two integers. (interval)
1634 = 1 * 1 * 1 * 1 + 6 * 6 * 6 * 6 + 3 * 3 * 3 * 3 + 4 * 4 * 4 *4
= 1 + 1296 + 81 + 256
= 1634
8208 = 8 * 8 * 8 * 8 + 2 * 2 * 2 * 2 + 0 * 0 * 0 * 0 + 8 * 8 * 8 * 8
= 4096 + 16 + 0 + 4096
= 8206
9474 = 9 * 9 * 9 * 9 + 4 * 4 * 4 *4 + 7 * 7 * 7 * 7 + 4 * 4 * 4 *4
= 6561 + 256 + 2401 + 256
= 9474
我們下面使用的方法很簡單。我們查看該範圍內的所有數字。對於每個數字,我們首先確定其中的位數。使當前數字的小數位數總和為數字「n」。然後我們計算每個數字的第 n 次方的和。如果總和大於「K」,那麼我們記錄結果。
代碼:
# First we will import required module:
import math
lower1 = int(input("Please enter the lower range of the integer: "))
upper1 = int(input("Please enter the upper range of the integer: "))
print("The Armstrong Numbers Between Two Given Integers:")
for num_1 in range(lower1, upper1 + 1):
# Now, we will set the order of number
order1 = len(str(num_1))
# here, we are initializing sum
sum = 0
temp1 = num_1
while temp1 > 0:
digit1 = temp1 % 10
sum += digit1 ** order1
temp1 //= 10
if num_1 == sum:
print(num_1)
輸出:
Please enter the lower range of the integer: 1000
Please enter the upper range of the integer: 10000
The Armstrong Numbers Between Two Given Integers:
1634
8208
9474
結論
在本教程中,我們討論了如何使用 Python 編程列印兩個給定整數之間的阿姆斯特朗數。
原創文章,作者:NI5SH,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/130068.html