Program to check Armstrong Number in Python

by | Jan 15, 2021 | Python Programs

Home » Python » Python Programs » Program to check Armstrong Number in Python

Introduction

In this section we’ll learn to check whether the given number is Armstrong number or not. A number is said be Armstrong number of order n if:

abc….n = power(a,n) + power(b,n) + power(c,n) +……..+ powe(n,n)

Program to check Armstrong Number

Program

# Function to calculate the power b of number a

def pow(a,b):

    if b == 0:

        return 1

    if b%2 == 0:

        return pow(a,b//2)*pow(a,b//2)

    return a*pow(a,b//2)*pow(a,b//2)




#Function to calculate the order of number

def ord(order):

    x = 0

    while(order!=0):

        x += 1

        order = order//10

    return x




#Check Armstrong number

def check_Armstrong(n):

    x = ord(n)

    temp = n

    sum_res = 0

    while(temp!=0):

        temp1 = temp%10

        sum_res = sum_res+pow(temp1,x)

        temp = temp//10

    return (sum_res == 0)

   

n = 268

print(check_Armstrong(n))

Output:

Program to check Armstrong Number Output

Explanation

In the above program, we have created three functions pow(), ord() and check_armstrong(). The pow() function will calculate the power of digits, ord() function will calculate the order of number i.e. the number of digits in a given number and the check_armstrong() function will verify whether the it is Armstrong number or not. The function check_armstrong() returns the boolean value depending upon the given number.

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author