Python – Check if Number is Armstrong

Python Program to Check if Number is Armstrong

An n-digit number abcd.. is said to be an Armstrong number if it obeys the following condition.

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

In this tutorial, we shall write a Python function, and also go through examples, where we shall check if a given number is an Armstrong number or not.

Python Armstrong Function

The following function armstrong()can take a number as argument and check if this number is Armstrong or not. The function returns True if the given number if Armstrong, or False if not.

def armstrong(num):
	num = str(num)
	n = len(num)
	result = 0
	# compute pow(a,n)+pow(b,n)+...
	for i in num:
		result += pow(int(i), n)
		#no need to check if part of the expansion exceeds the given number
		if ( result > int(num) ):
			break
	#check if given number equals expansion
	if ( int(num) == result ):
		return True
	else:
		return False

In the above function, we have defined following sequence of steps.

  • Consider that the argument is string. If not, we are converting it to string using str(num).
  • n = len(num) finds the value of n, the number of digits in the given number.
  • In the Python For Loop, we computed the sum of powers.
  • In the Python If Else statement, we are checking if the argument is equal to the result of sum of powers equation. If the two numbers are equal, then the given number is Armstrong, else not.

Example 1: Check if Given Number is Armstrong

In the following example, we will read a number from the user and check if that is an Armstrong Number.

Python Program

def armstrong(num):
	num = str(num)
	n = len(num)
	result = 0
	# compute pow(a,n)+pow(b,n)+...
	for i in num:
		result += pow(int(i), n)
		#no need to check if part of the expansion exceeds the given number
		if ( result > int(num) ):
			break
	#check if given number equals expansion
	if ( int(num) == result ):
		return True
	else:
		return False

# Read the number as a string
num = input('Enter a number: ')
result = armstrong(num)
print('Is ',num,' an Armstrong Number? ',result,sep="")
Copy

Output

C:\python>python example.py
Enter a number: 123
Is 123 an Armstrong Number? False

C:\python>python example.py
Enter a number: 153
Is 153 an Armstrong Number? True

C:\python>python example.py
Enter a number: 1634
Is 1634 an Armstrong Number? True

C:\python>python example.py
Enter a number: 413
Is 413 an Armstrong Number? False

Summary

In this tutorial of Python Examples, we learned how to check if a given number is an Armstrong number or not.

Related Tutorials

Code copied to clipboard successfully 👍