A Python implementation to check whether the input number is an Armstrong number (a number that is equal to the sum of its digits each raised to the power of the number of digits) or not.

Hey CodeSpeeder!

Numbers are amazing when it comes to finding patterns within the number themselves.

Consider a number, for example, 153. There are a total of 3 digits in the number: 1, 5, and 3 whose 3rd power is 1, 125, and 9 respectively. Add them up and you'll get 153, the input number again. Isn't this fascinating! Such numbers are specially named as **Armstrong Number.**

Let's mathematically formulate this! Consider a number **num** with n digits be expressed as d_{n}d_{n-1}...d_{1}. **num** is an Armstrong number if the following condition is satisfied:

**d _{n}d_{n-1}...d_{1} = (d_{n})^{n}_{ }+ (d_{n-1})^{n }+...+ (d_{1})^{n} **

For example:

Number 153 is a 3-digit number. Hence, n=3. From the above condition, LHS=153 while RHS = 1^{3 }+ 5^{3 }+ 3^{3} = 153 = LHS. 153 is an Armstrong number.

Number 135 is also a 3-digit number. Here, LHS=135 while RHS = 1^{3 }+ 3^{3 }+ 5^{3} = 153 = RHS. Hence, 135 is not an Armstrong number.

The following is the** Python** implementation for checking whether the input number is an Armstrong number or not:

# function to check if the number n # is Armstrong number or not def isArmstrongNumber(num): sumVal = 0 # Sum value n = len(str(num)) # total digits in the number num # calculate the sum of the nth power of each digit in number num for digit in str(num): sumVal += int(digit) ** n # if the sumVal is equal to input number num, # num is an Armstrong number if sumVal == num: return True else: return False

The below is the driver code to check the function **isArmstrongNumber()** on various test-cases:

# Test-case 1: 153 is an Armstrong Number print("Is 153 an Armstrong Number? - ", isArmstrongNumber(153)) # Test-case 2: 135 is not an Armstrong Number print("Is 135 an Armstrong Number? - ", isArmstrongNumber(135)) # Test-case 3: 407 is an Armstrong Number print("Is 407 an Armstrong Number? - ", isArmstrongNumber(407)) # Test-case 4: 1634 is an Armstrong Number print("Is 1634 an Armstrong Number? - ", isArmstrongNumber(1634))

# Test-case 5: 115132219018763992565095597973971522401 is an Armstrong Number

print("Is 115,132,219,018,763,992,565,095,597,973,971,522,401 an Armstrong Number? - ", isArmstrongNumber(115132219018763992565095597973971522401))

The output of the following code is:

Is 153 an Armstrong Number? - True Is 135 an Armstrong Number? - False Is 407 an Armstrong Number? - True Is 1634 an Armstrong Number? - True Is 115,132,219,018,763,992,565,095,597,973,971,522,401 an Armstrong Number? - True

There are only 89 Armstrong numbers of which the largest is 115,132,219,018,763,992,565,095,597,973,971,522,401

with 39 digits. (reference)^{}

Submitted by Kalki Pareshkumar Bhavsar (KalkiBhavsar)

Download packets of source code on Coders Packet

## Comments