VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-for-armstrong-numbers/

⇱ Program for Armstrong Numbers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program for Armstrong Numbers

Last Updated : 20 Jun, 2025

Given a number x, determine whether the given number is Armstrong's number or not. A positive integer of n digits is called an Armstrong number of order n (order is the number of digits) if

abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + ....

Here a, b, c and d are digits of input number abcd.....

Examples

Input: n = 153
Output: true
Explanation: 153 is an Armstrong number, 1*1*1 + 5*5*5 + 3*3*3 = 153

Input: n = 9474
Output: true
Explanation: 94 + 44 + 74 + 44 = 6561 + 256 + 2401 + 256 = 9474

Input: n = 123
Output: false
Explanation: 1³ + 2³ + 3³ = 1 + 8 + 27 = 36

[Approach 1] Naive Approach

  1. The idea is to first count the number of digits (or find the order). Let the number of digits be n. 
  2. For every digit r in input number x, compute rn
  3. If the sum of all such values is equal to x, then return true, else false. 

Output
true

Time Complexity: O(d*log(d)), where d is the number of digits in n, since we compute the power for each digit.
Space Complexity: O(1)

[Approach 2] Using Numeric Strings

The idea is to determine if a number is an Armstrong number by first converting it to a string to easily access its digits and count them. Each digit is then raised to the power of the total number of digits, and the results are summed. If this sum is equal to the original number, it is classified as an Armstrong number. This approach leverages simple string manipulation and power calculation to perform the check efficiently.


Output
true

Time Complexity: O(d*log(d)), where d is the number of digits in n, since we compute the power for each digit.
Space Complexity: O(1)

Comment
Article Tags: