Write a program of armstrong number in python - Armstrong number program in python - Python Programs

 Armstrong Number Program In Python 



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

Python Code: 

def is_armstrong(n):

    """

    Returns True if the given positive integer n is an Armstrong number, False                  otherwise.

    """

    # Convert the number to a string to count the number of digits

    num_str = str(n)

    num_digits = len(num_str)

    # Compute the sum of the nth powers of the digits

    sum = 0

    for digit in num_str:

        sum += int(digit) ** num_digits

    # Check if the sum is equal to the original number

    return sum == n 

Here is the Practical of the above program in Jupyter Notebook



# Example usage

print(is_armstrong(153))  # True (since 1^3 + 5^3 + 3^3 = 153)

print(is_armstrong(371))  # True (since 3^3 + 7^3 + 1^3 = 371)

print(is_armstrong(9474))  # True (since 9^4 + 4^4 + 7^4 + 4^4 = 9474)

print(is_armstrong(9475))  # False 

The is_armstrong function takes a positive integer n as input and returns True if n is an Armstrong number, and False otherwise. To check if a number is an Armstrong number, we first convert the number to a string to count the number of digits, and then compute the sum of the nth powers of each digit, where n is the number of digits. Finally, we check if the sum is equal to the original number. 

For example, to check if 153 is an Armstrong number, we first compute the number of digits (which is 3), and then compute 1^3 + 5^3 + 3^3 = 153, which is equal to the original number. Therefore, 153 is an Armstrong number. 

Note that this implementation assumes that the input number is positive. If you want to handle negative or non-integer input, you should add appropriate input validation.

Comments