An Armstrong number, also known as a narcissistic number or a pluperfect digital invariant (PPDI), is a number that is equal to the sum of its own digits each raised to the power of the number of digits. For example, the number 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153. In other words, an n
-digit number is an Armstrong number if the sum of its digits each raised to the power n
is equal to the number itself.
Here’s a code for printing a series of Armstrong numbers between 1 to 1000 in Python along with a line-by-line explanation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
for num in range(1, 1001): # initialize sum sum = 0 # find the number of digits in num temp = num while temp > 0: digit = temp % 10 sum += digit ** 3 temp //= 10 if num == sum: print(num) |
Output:
1 2 3 4 5 6 7 |
1 153 370 371 407 |
Explanation:
for num in range(1, 1001):
: This line starts a for loop that iterates over all the numbers between 1 and 1000.sum = 0
: This line initializes a variablesum
to store the sum of cubes of digits.temp = num
: This line initializes a variabletemp
to store a copy of the current number.while temp > 0:
: This line starts a while loop that continues until all digits have been processed.digit = temp % 10
: This line extracts the last digit oftemp
by taking the modulo 10.sum += digit ** 3
: This line adds the cube of the extracted digit to thesum
.temp //= 10
: This line removes the last digit oftemp
by floor-dividing it by 10.if num == sum:
: This line checks if the sum of cubes of digits is equal to the original number.print(num)
: This line prints the number if it is an Armstrong number.
This code will print all the Armstrong numbers between 1 and 1000.