AlgoViz

Check if the Number is Armstrong

Easy

Sum of digits raised to the digit count

Problem

An Armstrong number equals the sum of each of its digits raised to the power of the number of digits. Return whether n is Armstrong.

In simple words

Raise each digit to the power of how many digits there are, add them, and see if you get the number back.

The idea

Count the digits first, then walk the digits again summing each one raised to that power, and compare with the original. The digit count has to come first because it is the exponent every term uses.

The trick

  • Two passes: one to count digits, one to accumulate the powered sum.
  • Every single-digit number is trivially an Armstrong number.

This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.

153
0

Step 1 of 2. Here's the example — n = 153 Values: 153.

1/2
Optimal
timeO(log n)spaceO(1)
1k = number of digits of n2sum = 0, x = n3while x > 0:4  d = x % 105  sum += d^k6  x = x / 107return sum == n

Input

array
[153]

Output

answer

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
n = 153
Output:
true
Explanation:
1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153.

Example 2

Input:
n = 371
Output:
true
Explanation:
3^3 + 7^3 + 1^3 = 27 + 343 + 1 = 371.

Example 3

Input:
n = 123
Output:
false
Explanation:
1^3 + 2^3 + 3^3 = 36, which is not 123.

Practice this problem:GeeksforGeeks(opens in a new tab)

Finished the walkthrough? Add it to your streak.