Python Program to Check Armstrong Number.

Given a number x, write a Python program to check whether the given number is an Armstrong number or not. 

An Armstrong number, also known as a narcissistic number or a pluperfect digital invariant, is a number that is equal to the sum of its own digits raised to the power of the number of digits. ()


For example, the number 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153.

Example:

Input: num = 1634
Output: 1634 is an Armstrong Number.

Explanation: 1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1634

Input: num = 130
Output: 130 is not an Armstrong Number.

Explanation: 1*1*1 + 3*3*3 + 0*0*0 = 28


Python Program to check if the given number is Armstrong Number.

def is_armstrong_number(number):
    # convert the number to a string and find the number of digits
    num_str = str(number)
    num_digits = len(num_str)

    # initialize a variable to store the sum of the digits raised to the power of the number of digits
    sum_of_digits = 0

    # loop through each digit in the number
    for digit in num_str:
        # raise the digit to the power of the number of digits and add it to the sum
        sum_of_digits += int(digit) ** num_digits

    # return True if the sum is equal to the number, and False otherwise
    return sum_of_digits == number

# take input from the user
number = int(input("Enter a number: "))

# check if the number is an Armstrong number
if is_armstrong_number(number):
    print(number, "is an Armstrong number.")
else:
    print(number, "is not an Armstrong number.")
Output:
Enter a number: 153
153 is an Armstrong number.
  • Time Complexity: O(log n)
  • Space Complexity: O(1)
Code Explanation
  • The program defines a function is_armstrong_number to check if a given number is an Armstrong number.
  • The function first converts the number to a string and finds the number of digits by finding the length of the string.
  • The function then initializes a variable sum_of_digits to store the sum of the digits raised to the power of the number of digits.
  • The function then loops through each digit in the number, raises the digit to the power of the number of digits, and adds the result to the sum_of_digits.
  • The function then returns True if the sum_of_digits is equal to the original number, and False otherwise.

Read More:

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS