Program for Armstrong Numbers
- Difficulty Level : Easy
- Last Updated : 23 Aug, 2022
Given a number x, determine whether the given number is Armstrong number or not.
A positive integer of n digits is called an Armstrong number of order n (order is number of digits) if.
![]()
abcd… = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + ….
Example:
Input : 153
Output : Yes
153 is an Armstrong number.
1*1*1 + 5*5*5 + 3*3*3 = 153
Input : 120
Output : No
120 is not a Armstrong number.
1*1*1 + 2*2*2 + 0*0*0 = 9
Input : 1253
Output : No
1253 is not a Armstrong Number
1*1*1*1 + 2*2*2*2 + 5*5*5*5 + 3*3*3*3 = 723
Input : 1634
Output : Yes
1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1634
Recommended PracticeApproach: The idea is to first count number digits (or find order). Let the number of digits be n. For every digit r in input number x, compute rn. If sum of all such values is equal to n, then return true, else false.
C++
// C++ program to determine whether the number is// Armstrong number or not#include <bits/stdc++.h>usingnamespacestd;/* Function to calculate x raised to the power y */intpower(intx, unsignedinty){if(y == 0)return1;if(y % 2 == 0)returnpower(x, y / 2) * power(x, y / 2);returnx * power(x, y / 2) * power(x, y / 2);}/* Function to calculate order of the number */intorder(intx){intn = 0;while(x) {n++;x = x / 10;}returnn;}// Function to check whether the given number is// Armstrong number or notboolisArmstrong(intx){// Calling order functionintn = order(x);inttemp = x, sum = 0;while(temp) {intr = temp % 10;sum += power(r, n);temp = temp / 10;}// If satisfies Armstrong conditionreturn(sum == x);}// Driver Programintmain(){intx = 153;cout << boolalpha << isArmstrong(x) << endl;x = 1253;cout << boolalpha << isArmstrong(x) << endl;return0;}C
// C program to find Armstrong number#include <stdio.h>/* Function to calculate x raised to the power y */intpower(intx, unsignedinty){if(y == 0)return1;if(y % 2 == 0)returnpower(x, y / 2) * power(x, y / 2);returnx * power(x, y / 2) * power(x, y / 2);}/* Function to calculate order of the number */intorder(intx){intn = 0;while(x) {n++;x = x / 10;}returnn;}// Function to check whether the given number is// Armstrong number or notintisArmstrong(intx){// Calling order functionintn = order(x);inttemp = x, sum = 0;while(temp) {intr = temp % 10;sum += power(r, n);temp = temp / 10;}// If satisfies Armstrong conditionif(sum == x)return1;elsereturn0;}// Driver Programintmain(){intx = 153;if(isArmstrong(x) == 1)printf("True\n");elseprintf("False\n");x = 1253;if(isArmstrong(x) == 1)printf("True\n");elseprintf("False\n");return0;}Java
// Java program to determine whether the number is// Armstrong number or notpublicclassArmstrong {/* Function to calculate x raised to thepower y */intpower(intx,longy){if(y ==0)return1;if(y %2==0)returnpower(x, y /2) * power(x, y /2);returnx * power(x, y /2) * power(x, y /2);}/* Function to calculate order of the number */intorder(intx){intn =0;while(x !=0) {n++;x = x /10;}returnn;}// Function to check whether the given number is// Armstrong number or notbooleanisArmstrong(intx){// Calling order functionintn = order(x);inttemp = x, sum =0;while(temp !=0) {intr = temp %10;sum = sum + power(r, n);temp = temp /10;}// If satisfies Armstrong conditionreturn(sum == x);}// Driver Programpublicstaticvoidmain(String[] args){Armstrong ob =newArmstrong();intx =153;System.out.println(ob.isArmstrong(x));x =1253;System.out.println(ob.isArmstrong(x));}}Python
# Python program to determine whether the number is# Armstrong number or not# Function to calculate x raised to the power ydefpower(x, y):ify==0:return1ify%2==0:returnpower(x, y/2)*power(x, y/2)returnx*power(x, y/2)*power(x, y/2)# Function to calculate order of the numberdeforder(x):# variable to store of the numbern=0while(x !=0):n=n+1x=x/10returnn# Function to check whether the given number is# Armstrong number or notdefisArmstrong(x):n=order(x)temp=xsum1=0while(temp !=0):r=temp%10sum1=sum1+power(r, n)temp=temp/10# If condition satisfiesreturn(sum1==x)# Driver Programx=153(isArmstrong(x))x=1253(isArmstrong(x))Python3
# python3 >= 3.6 for typehint support# This example avoids the complexity of ordering# through type conversions & string manipulationdefisArmstrong(val:int)->bool:"""val will be tested to see if its an Armstrong number.Arguments:val {int} -- positive integer only.Returns:bool -- true is /false isn't"""# break the int into its respective digitsparts=[int(_)for_instr(val)]# begin test.counter=0for_inparts:counter+=_**3return(counter==val)# Check Armstrong number(isArmstrong(153))(isArmstrong(1253))C#
// C# program to determine whether the// number is Armstrong number or notusingSystem;publicclassGFG {// Function to calculate x raised// to the power yintpower(intx,longy){if(y == 0)return1;if(y % 2 == 0)returnpower(x, y / 2) * power(x, y / 2);returnx * power(x, y / 2) * power(x, y / 2);}// Function to calculate// order of the numberintorder(intx){intn = 0;while(x != 0) {n++;x = x / 10;}returnn;}// Function to check whether the// given number is Armstrong number// or notboolisArmstrong(intx){// Calling order functionintn = order(x);inttemp = x, sum = 0;while(temp != 0) {intr = temp % 10;sum = sum + power(r, n);temp = temp / 10;}// If satisfies Armstrong conditionreturn(sum == x);}// Driver CodepublicstaticvoidMain(){GFG ob =newGFG();intx = 153;Console.WriteLine(ob.isArmstrong(x));x = 1253;Console.WriteLine(ob.isArmstrong(x));}}// This code is contributed by Nitin Mittal.Javascript
<script>// JavaScript program to determine whether the// number is Armstrong number or not// Function to calculate x raised// to the power yfunctionpower(x, y){if( y == 0)return1;if(y % 2 == 0)returnpower(x, parseInt(y / 2, 10)) *power(x, parseInt(y / 2, 10));returnx * power(x, parseInt(y / 2, 10)) *power(x, parseInt(y / 2, 10));}// Function to calculate// order of the numberfunctionorder(x){let n = 0;while(x != 0){n++;x = parseInt(x / 10, 10);}returnn;}// Function to check whether the// given number is Armstrong number// or notfunctionisArmstrong(x){// Calling order functionlet n = order(x);let temp = x, sum = 0;while(temp != 0){let r = temp % 10;sum = sum + power(r, n);temp = parseInt(temp / 10, 10);}// If satisfies Armstrong conditionreturn(sum == x);}let x = 153;if(isArmstrong(x)){document.write("True"+"</br>");}else{document.write("False"+"</br>");}x = 1253;if(isArmstrong(x)){document.write("True");}else{document.write("False");}</script>Outputtrue falseThe above approach can also be implemented in a shorter way as:
C++
#include <iostream>usingnamespacestd;intmain() {intn = 153;inttemp = n;intp = 0;/*function to calculatethe sum of individual digits*/while(n > 0) {intrem = n % 10;p = (p) + (rem * rem * rem);n = n / 10;}/* condition to check whetherthe value of P equalsto user input or not. */if(temp == p) {cout<<("Yes. It is Armstrong No.");}else{cout<<("No. It is not an Armstrong No.");}return0;}// This code is contributed by sathiyamoorthics19C
#include <stdio.h>intmain() {intn = 153;inttemp = n;intp = 0;/*function to calculatethe sum of individual digits*/while(n > 0) {intrem = n % 10;p = (p) + (rem * rem * rem);n = n / 10;}/* condition to check whetherthe value of P equalsto user input or not. */if(temp == p) {printf("Yes. It is Armstrong No.");}else{printf("No. It is not an Armstrong No.");}return0;}// This code is contributed by sathiyamoorthics19Java
// Java program to determine whether the number is// Armstrong number or notpublicclassArmstrongNumber {publicstaticvoidmain(String[] args){intn =153;inttemp = n;intp =0;/*function to calculatethe sum of individual digits*/while(n >0) {intrem = n %10;p = (p) + (rem * rem * rem);n = n /10;}/* condition to check whetherthe value of P equalsto user input or not. */if(temp == p) {System.out.println("Yes. It is Armstrong No.");}else{System.out.println("No. It is not an Armstrong No.");}}}Python3
n=153; temp=n; p=0# function to calculate# the sum of individual digitswhile(n >0):rem=n%10;p=(p)+(rem*rem*rem);n=n//10;iftemp==p:("armstrong")else:("not a armstrong number")# This code is contributed by ksrikanth0498.C#
// C# program to determine whether the number is// Armstrong number or notusingSystem;publicclassArmstrongNumber {publicstaticvoidMain(string[] args){intn = 153;inttemp = n;intp = 0;/*function to calculatethe sum of individual digits*/while(n > 0) {intrem = n % 10;p = (p) + (rem * rem * rem);n = n / 10;}/* condition to check whetherthe value of P equalsto user input or not. */if(temp == p) {Console.WriteLine("Yes. It is Armstrong No.");}else{Console.WriteLine("No. It is not an Armstrong No.");}}}// This code is contributed by phasing17Javascript
// JavaScript implementation of the approachlet n = 153;let temp = n;let p = 0;/*function to calculatethe sum of individual digits */while(n > 0) {let rem = n % 10;p = (p) + (rem * rem * rem);n = Math.floor(n / 10);}/* condition to check whetherthe value of P equalsto user input or not. */if(temp == p) {console.log("Yes. It is Armstrong No.");}else{console.log("No. It is not an Armstrong No.");}// This code is contributed by phasing17OutputYes. It is Armstrong No.Time complexity: O(log n)
Auxiliary Space:O(1)
Find nth Armstrong number
Input : 9
Output : 9
Input : 10
Output : 153
C++
// C++ Program to find// Nth Armstrong Number#include <bits/stdc++.h>#include <math.h>usingnamespacestd;// Function to find Nth Armstrong NumberintNthArmstrong(intn){intcount = 0;// upper limit from integerfor(inti = 1; i <= INT_MAX; i++) {intnum = i, rem, digit = 0, sum = 0;// Copy the value for num in numnum = i;// Find total digits in numdigit = (int)log10(num) + 1;// Calculate sum of power of digitswhile(num > 0) {rem = num % 10;sum = sum +pow(rem, digit);num = num / 10;}// Check for Armstrong numberif(i == sum)count++;if(count == n)returni;}}// Driver Functionintmain(){intn = 12;cout << NthArmstrong(n);return0;}// This Code is Contributed by 'jaingyayak'Java
// Java Program to find// Nth Armstrong Numberimportjava.lang.Math;classGFG {// Function to find Nth Armstrong NumberstaticintNthArmstrong(intn){intcount =0;// upper limit from integerfor(inti =1; i <= Integer.MAX_VALUE; i++) {intnum = i, rem, digit =0, sum =0;// Copy the value for num in numnum = i;// Find total digits in numdigit = (int)Math.log10(num) +1;// Calculate sum of power of digitswhile(num >0) {rem = num %10;sum = sum + (int)Math.pow(rem, digit);num = num /10;}// Check for Armstrong numberif(i == sum)count++;if(count == n)returni;}returnn;}// Driver Codepublicstaticvoidmain(String[] args){intn =12;System.out.println(NthArmstrong(n));}}// This code is contributed by Code_Mech.Python3
# Python3 Program to find Nth Armstrong Numberimportmathimportsys# Function to find Nth Armstrong NumberdefNthArmstrong(n):count=0# upper limit from integerforiinrange(1, sys.maxsize):num=irem=0digit=0sum=0# Copy the value for num in numnum=i# Find total digits in numdigit=int(math.log10(num)+1)# Calculate sum of power of digitswhile(num >0):rem=num%10sum=sum+pow(rem, digit)num=num//10# Check for Armstrong numberif(i==sum):count+=1if(count==n):returni# Driver Coden=12(NthArmstrong(n))# This code is contributed by chandan_jnuC#
// C# Program to find// Nth Armstrong NumberusingSystem;classGFG {// Function to find Nth Armstrong NumberstaticintNthArmstrong(intn){intcount = 0;// upper limit from integerfor(inti = 1; i <=int.MaxValue; i++) {intnum = i, rem, digit = 0, sum = 0;// Copy the value for num in numnum = i;// Find total digits in numdigit = (int)Math.Log10(num) + 1;// Calculate sum of power of digitswhile(num > 0) {rem = num % 10;sum = sum + (int)Math.Pow(rem, digit);num = num / 10;}// Check for Armstrong numberif(i == sum)count++;if(count == n)returni;}returnn;}// Driver CodepublicstaticvoidMain(){intn = 12;Console.WriteLine(NthArmstrong(n));}}// This code is contributed by Code_Mech.PHP
<?php// PHP Program to find// Nth Armstrong Number// Function to find// Nth Armstrong NumberfunctionNthArmstrong($n){$count= 0;// upper limit// from integerfor($i= 1;$i<= PHP_INT_MAX;$i++){$num=$i;$rem;$digit= 0;$sum= 0;// Copy the value// for num in num$num=$i;// Find total// digits in num$digit= (int) log10($num) + 1;// Calculate sum of// power of digitswhile($num> 0){$rem=$num% 10;$sum=$sum+ pow($rem,$digit);$num= (int)$num/ 10;}// Check for// Armstrong numberif($i==$sum)$count++;if($count==$n)return$i;}}// Driver Code$n= 12;echoNthArmstrong($n);// This Code is Contributed// by akt_mit?>Javascript
<script>// Javascript program to find Nth Armstrong Number// Function to find Nth Armstrong NumberfunctionNthArmstrong(n){let count = 0;// Upper limit from integerfor(let i = 1; i <= Number.MAX_VALUE; i++){let num = i, rem, digit = 0, sum = 0;// Copy the value for num in numnum = i;// Find total digits in numdigit = parseInt(Math.log10(num), 10) + 1;// Calculate sum of power of digitswhile(num > 0){rem = num % 10;sum = sum + Math.pow(rem, digit);num = parseInt(num / 10, 10);}// Check for Armstrong numberif(i == sum)count++;if(count == n)returni;}returnn;}// Driver codelet n = 12;document.write(NthArmstrong(n));// This code is contributed by rameshtravel07</script>C
// C Program to find// Nth Armstrong Number#include <stdio.h>#include <math.h>#include<limits.h>// Function to find Nth Armstrong NumberintNthArmstrong(intn){intcount = 0;// upper limit from integerfor(inti = 1; i <= INT_MAX; i++) {intnum = i, rem, digit = 0, sum = 0;// Copy the value for num in numnum = i;// Find total digits in numdigit = (int)log10(num) + 1;// Calculate sum of power of digitswhile(num > 0) {rem = num % 10;sum = sum +pow(rem, digit);num = num / 10;}// Check for Armstrong numberif(i == sum)count++;if(count == n)returni;}}// Driver Functionintmain(){intn = 12;printf("%d", NthArmstrong(n));return0;}// This Code is Contributed by//'sathiyamoorthics19'Output371Using Numeric Strings:
When considering the number as a string we can access any digit we want and perform operations
C++
// C++ code to implement the approach#include <bits/stdc++.h>usingnamespacestd;string armstrong(intn){string number = to_string(n);n = number.length();longlongoutput = 0;for(chari : number)output = output + (long)pow((i -'0'), n);if(output == stoll(number))return("True");elsereturn("False");}intmain(){cout << armstrong(153) << endl;cout << armstrong(1253) << endl;}// This code is contributed by phasing17Java
publicclassarmstrongNumber{publicvoidisArmstrong(String n){char[] s = n.toCharArray();intsize = s.length;intsum =0;for(charnum : s){inttemp =1;inti= Integer.parseInt(Character.toString(num));for(intj =0; j <= size -1; j++){temp *= i;}sum += temp;}if(sum == Integer.parseInt(n)){System.out.println("True");}else{System.out.println("False");}}publicstaticvoidmain(String[] args){armstrongNumber am =newarmstrongNumber();am.isArmstrong("153");am.isArmstrong("1253");}}Python3
defarmstrong(n):number=str(n)n=len(number)output=0foriinnumber:output=output+int(i)**nifoutput==int(number):return(True)else:return(False)(armstrong(153))(armstrong(1253))C#
usingSystem;publicclassarmstrongNumber {publicvoidisArmstrong(String n){char[] s = n.ToCharArray();intsize = s.Length;intsum = 0;foreach(charnumins){inttemp = 1;inti = Int32.Parse(char.ToString(num));for(intj = 0; j <= size - 1; j++) {temp *= i;}sum += temp;}if(sum == Int32.Parse(n)) {Console.WriteLine("True");}else{Console.WriteLine("False");}}publicstaticvoidMain(String[] args){armstrongNumber am =newarmstrongNumber();am.isArmstrong("153");am.isArmstrong("1253");}}// This code is contributed by umadevi9616Javascript
<script>functionarmstrong(n){let number =newString(n)n = number.lengthlet output = 0for(let i of number)output = output + parseInt(i)**nif(output == parseInt(number))return("True"+"<br>")elsereturn("False"+"<br>")}document.write(armstrong(153))document.write(armstrong(1253))// This code is contributed by _saurabh_jaiswal.</script>OutputTrue FalseTime Complexity: O(n).
Auxiliary Space: O(1).References:
http://www.cs.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/arms.html
http://www.programiz.com/c-programming/examples/check-armstrong-number
This article is contributed by Rahul Agrawal .If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
My Personal Notes arrow_drop_upRecommended ArticlesPage :Article Contributed By :Improved By :Article Tags :Practice Tags :



