In order to understand if a number is an Armstrong number in Python, one should be well versed with the following topics:
A positive integer is called an Armstrong number of order n
if it is equal to the sum of the powers of its own digits. For example:
abc…(up to n digits) = a^n + b^n +c^n ...(up to n digits)
In the case of the Armstrong number of 3 digits, it is equal to the sum of the cubes for each digit. For example, the number 407 = 4 x 4 x 4 + 0 x 0 x 0 + 7 x 7 x 7 ⇒ 407 is an Armstrong number.
Let’s take a look at the code below.
import java.util.Scanner; import java.lang.Math; class CheckArmstrongNumber { static boolean isArmstrong(int n) { int temp, digits=0, last=0, sum=0; temp = n; while(temp>0) { temp = temp/10; digits++; } temp = n; while(temp>0) { last = temp % 10; sum += (Math.pow(last, digits)); temp = temp/10; } if(n == sum) return true; else return false; } public static void main(String args[]) { int num; Scanner sc= new Scanner(System.in); num = sc.nextInt(); if(isArmstrong(num)) System.out.print(num + " is Armstrong."); else System.out.print(num + " is not Armstrong."); } }
Enter the input below
In lines 1 and 2, we import the required header files.
In lines 5 to 25, we create a function in which we run a loop to find the sum of the power of the order of each digit. We obtain the unit digit each time with the modulus operator %
, since the remainder of the number when it is divided by 10 is the last digit of that number.
In lines 15 to 20, we take the power of the order of the number with the pow()
function.
In lines 29 to 31, we read the input number from the user.
In lines 33 to 37, we call the isArmstrong()
function to check whether the number is Armstrong and print the statement accordingly.
RELATED TAGS
CONTRIBUTOR
View all Courses