Followers

Showing posts with label Armstrong Number. Show all posts
Showing posts with label Armstrong Number. Show all posts

Wednesday, April 26, 2023

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 its own digits raised to the power of the number of digits in the number. In other words, if we take each digit of a number, raise it to the power of the number of digits, and add up all the resulting numbers, and the sum is equal to the original number, then that number is called an Armstrong number.

For example, 153 is an Armstrong number because:

1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153

Some other examples of Armstrong numbers are: 1, 370, 371, 407, 1634, 8208, and 9474.

Here's a Python program to check if a given number is an Armstrong number or not :

python
# Function to check if a number is an Armstrong number def is_armstrong(n): # Find the number of digits num_digits = len(str(n)) # Compute the sum of the cubes of the digits sum = 0 temp = n while temp > 0: digit = temp % 10 sum += digit ** num_digits temp //= 10 # Check if the number is an Armstrong number if n == sum: return True else: return False # Get the number to check from the user num = int(input("Enter a number: ")) # Check if the number is an Armstrong number if is_armstrong(num): print(num, "is an Armstrong number") else: print(num, "is not an Armstrong number")

In this program, I first define a function is_armstrong() to check if a number is an Armstrong number or not. This function takes a number n as input and returns True if it's an Armstrong number, or False if it's not.

To check if a number is an Armstrong number, I first find the number of digits in the number. I then compute the sum of the cubes of the digits by extracting each digit using the modulus operator (%), raising it to the power of the number of digits, and adding it to a running sum. Finally, I check if the sum is equal to the original number, and return True if it is, or False otherwise.

I then ask the user to enter a number to check. I call the is_armstrong() function on the number, and print a message indicating whether it's an Armstrong number or not based on the function's return value.