Write a Program to Check Armstrong Number or not.
Armstrong Number in Mathematics: An Armstrong number (also known as a narcissistic number, pluperfect digital invariant, or pluperfect digital number) is a number that is equal to the sum of its own digits raised to the power of the number of digits. In other words, an n-digit number abc… is an Armstrong number if a power n+b power n+c power n+… equals the number itself.
For example, 153 is an Armstrong number because 1 cube 3+5 cube 3+3 cube 3=153
Python Program to Check Armstrong Number:
Here’s a Python program that checks whether a given number is an Armstrong number or not:
num = int(input("Enter a number: "))
original_num = num
num_digits = len(str(num))
sum_of_powers = 0
while num > 0:
   digit = num % 10
   sum_of_powers += digit ** num_digits
   num //= 10
is_armstrong = original_num == sum_of_powers
print("Armstrong Number" if is_armstrong else "Not Armstrong Number")
Explanation:
- The program starts by taking an integer input from the user using the input() function and converting it into an integer using the int() function. This input is stored in the variable num.
- The variables original_num, num_digits, and sum_of_powers are initialized with the original number entered by the user, the number of digits in the number, and 0, respectively.
- The program calculates the sum of the powers of digits:
- Inside the while loop, the last digit of the number is extracted using the modulo operator % (num % 10), and its value raised to the power of num_digits is added to sum_of_powers.
- The last digit is removed from num using integer division (num //= 10).
- After the loop, the program compares original_num with sum_of_powers to determine if the number is an Armstrong number. If they’re equal, the number is an Armstrong number; otherwise, it’s not.
- The program prints “Armstrong Number” if is_armstrong is True, indicating that the number is an Armstrong number. Otherwise, it prints “Not Armstrong Number“.
Output 1 (Armstrong Number):
Enter a number: 153
Armstrong Number
In the first example, the user enters 153, which is an Armstrong number because
The program calculates the sum of the powers of its digits and finds that it’s equal to the original number, so it displays “Armstrong Number” as the output.
Output 2 (Not Armstrong Number):
Enter a number: 123
Not Armstrong Number
In the second example, the user enters 123, which is not an Armstrong number. The program calculates the sum of the powers of its digits and finds that it’s not equal to the original number, so it displays “Not Armstrong Number” as the output.