195. Python Program to Check If a Number Is an Armstrong Number
EasyPhase 1 · Warm-up
You know str(), len(), for loops and the ** sign. That is all you need here.
Overview
Checking for an Armstrong number is a common interview question. It tests if you can take a number apart into its digits and do maths with each one.
Problem Statement
Sven likes special numbers. Today Sven looks for Armstrong numbers.
An Armstrong number is a number that equals the sum of its digits, when each digit is raised to the power of the number of digits. "Raised to the power 3" means multiplied by itself 3 times: 5 to the power 3 is 5 × 5 × 5 = 125.
For example, 153 has 3 digits. 1 × 1 × 1 + 5 × 5 × 5 + 3 × 3 × 3 = 1 + 125 + 27 = 153. So 153 is an Armstrong number.
Read a number n. Print <n> is an Armstrong number or <n> is not an Armstrong number.
Steps
- Read the number. Also keep it as text, so you can loop over its digits.
- Count the digits. This count is the power.
- Loop over the digits. Raise each digit to the power, and add it to a total.
- If the total equals the number, it is an Armstrong number. Print the right line.
Examples
Example 1. Input 153 gives:
153 is an Armstrong number
Why: 153 has 3 digits, and 1 + 125 + 27 = 153.
Example 2. Input 154 gives:
154 is not an Armstrong number
Why: 1 + 125 + 64 = 190, and 190 is not 154.
Input
One whole number n (1 to 1000000). Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Output
One line: <n> is an Armstrong number or <n> is not an Armstrong number. The tests try 6 different inputs, also a number with one digit.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.