Python

How to Print a Series of Armstrong Numbers Between 1 to 1000 Using Python1 min read

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:




Output:

Explanation:

  1. for num in range(1, 1001):: This line starts a for loop that iterates over all the numbers between 1 and 1000.
  2. sum = 0: This line initializes a variable sum to store the sum of cubes of digits.
  3. temp = num: This line initializes a variable temp to store a copy of the current number.
  4. while temp > 0:: This line starts a while loop that continues until all digits have been processed.
  5. digit = temp % 10: This line extracts the last digit of temp by taking the modulo 10.
  6. sum += digit ** 3: This line adds the cube of the extracted digit to the sum.
  7. temp //= 10: This line removes the last digit of temp by floor-dividing it by 10.
  8. if num == sum:: This line checks if the sum of cubes of digits is equal to the original number.
  9. 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.

Leave a Comment