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:
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:
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 variable
sumto store the sum of cubes of digits.
temp = num: This line initializes a variable
tempto 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 of
tempby taking the modulo 10.
sum += digit ** 3: This line adds the cube of the extracted digit to the
temp //= 10: This line removes the last digit of
tempby 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.