Thursday, December 8, 2022

Python Program to Check Armstrong Number

In this post we'll see a Python program to check if a given number is an Armstrong number or not.

An Armstrong number is a number that is equal to the sum of the digits in a number raised to the power of number of digits in the number.

For example 371 is an Armstrong number. Since the number of digits here is 3, so-

371 = 33 + 73 + 13 = 27 + 343 + 1 = 371

Another Example is 9474, here the number of digits is 4, so

9474 = 94 + 44 + 74 + 44 = 6561 + 256 + 2401 + 256 = 9474

Check Armstrong number or not Python program

In the program user is prompted to input a number. Number of digits in that number is calculated using len() function that takes string as input that is why number is cast to str.

In the loop add each digit of the input number raised to the power of number of digits. After the control comes out of loop if sum and the input number are equal then it is an Armstrong number otherwise not.

def check_armstrong(num):
  digitsum = 0
  temp = num
  # getting length of number
  no_of_digits = len(str(num))
  while temp != 0:
    digit = temp % 10
    # sum digit raise to the power of no of digits
    digitsum += (digit ** no_of_digits)
    temp = temp // 10
  print('Sum of digits is',  digitsum)
  # if sum and original number equal then Armstrong number
  return True if (digitsum == num) else False

num = int(input('Enter a number: '))
flag = check_armstrong(num)
if flag:
  print(num, 'is an Armstrong number')
  print(num, 'is not an Armstrong number')


Enter a number: 371
Sum of digits is 371
371 is an Armstrong number

Enter a number: 12345
Sum of digits is 4425
12345 is not an Armstrong number

Enter a number: 54748
Sum of digits is 54748
54748 is an Armstrong number

That's all for this topic Python Program to Check Armstrong Number. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page

Related Topics

  1. Python Program to Check Prime Number
  2. Python Program to Display Fibonacci Series
  3. Python Program to Count Occurrences of Each Character in a String
  4. Python continue Statement With Examples
  5. String Slicing in Python

You may also like-

  1. Name Mangling in Python
  2. Python Generator, Generator Expression, Yield Statement
  3. Constructor in Python - __init__() function
  4. Multiple Inheritance in Python
  5. ArrayList in Java With Examples
  6. Callable And Future in Java Concurrency
  7. Nested Class And Inner Class in Java
  8. Spring MessageSource Internationalization (i18n) Support