Amstrong number in python

Amstrong number in python

An n digit number is called an amstrong number if, the number is equal to the sum  of nth power of its digits.

abc.. = an + bn + cn + ..

An amstrong number is also called as narcissistic number. A three digit number is called an Armstrong number if the number is equal to the sum of the cubes of its digits. 

For example,

370 is an amstrong number as, 33 + 73 + 03 = 370.

Here's a python program to check whether a number is amstrong number or not.

Procedure :

1. Start.

2. Define a function to count the digits of a number.

3. Get the number as input from the user.

4. Assign n to a temporary variable.

5. Count the number of digits of the number using the count digits function.

6. Initialize sum as 0.

7. loop until temp = 0

    => get the last digit of the number.

    => calculate the nth power of the last digit.

    => add the nth power of number to the sum.

    => remove the last digit from the number

8. check if the sum is equal to the number, if so print as amstrong number, else print not an amstrong number.

9. End


Code :

#function to count the number of digits

def count_digits(n):

digit_count = 0

while(n!=0):

#increment digit count

digit_count+=1

#number is divided using modulus operator

n=n//10

#return the digit count

return digit_count


#get the number as input from user

n = int(input("Enter the number : "))

#assign n to a temporary variable

temp = n

#calculate the number of digits using the count_digits function

digit = count_digits(n)

#initialize sum as 0

sum = 0

while(temp!=0):

#get the last digit of the number

num = temp%10

#add the nth power of the digit to sum

sum += num**digit

#remove the last digit from the number

temp=temp//10

#check if the sum is equal to the number, if so print as amstrong number, else print not an amstrong number

if(sum==n):

print("Amstrong number.")

else :

print("Not an amstrong number.")


Sample input 0 :

153

Sample output 0 :

Amstrong number

Explanation :

1 * 1* 1 = 1

5 * 5 * 5 = 125

3 * 3 * 3 = 27

sum = 1 + 125 + 27 = 153 = given number

Hence, 153 is an amstrong number.

Sample input 1 :

120

sample output 1 :

Not an amstrong number.

Explanation :

1 * 1 * 1 = 1

2 * 2 * 2 = 8

0 * 0 * 0 = 0

sum = 1 + 8 + 0 = 9

sum is not equal to the given number.

Hence, 120 is not an amstrong number.

Output screenshot :

amstrong number in python

amstrong number in python



Comments

Popular posts from this blog

Finding the percentage in python - HackerRank solution

HackerRank challenges with solutions (Rearrangement, Formula, Word sorting, Numbers, Sentence)

ginortS in Python - HackerRank solution