In this article we will learn Python program to check whether the given number is Armstrong or not. First let us understand what is Armstrong?. An Armstrong number is a number that is equal to the sum of the Nth power of its individual digits.
Let me take one example, 153 is a 3 digit Armstrong number then 1^3 +5^3+3^3=153
Now we will write the code to find Armstrong Number in Python Script:
print("Enter the number")
#get the number
number = int(input())
#store it in a temp
temp = int(number)
Sum = 0
#loop till the quotient is 0
while(temp != 0):
rem = temp % 10 #find reminder
Sum = Sum + (rem * rem * rem) #cube reminder and add it to the Sum
temp = temp / 10 #find quotient, if 0 then loop again
#if the entered number and the Sum value matches, it is an Armstrong number
if(number == Sum):
print ("Armstrong Number")
else:
print ("Not an Armstrong Number")
Output:
Enter the number: 153
Armstrong Number
Python program to check whether the given number is Armstrong or not using For loop:
Number = int(input("\n Enter the number: "))
# Initializing Sum and Number of Digits
Sum = 0
number = 0
# Calculating Number of individual digits
Temp = Number
while Temp > 0:
number = number + 1
Temp = Temp // 10
# Finding Armstrong Number
Temp = Number
for n in range(1, Temp + 1):
Reminder = Temp % 10
Sum = Sum + (Reminder ** number)
Temp //= 10
if Number == Sum:
print("\n %d is Armstrong Number.\n" %Number)
else:
print("\n %d is Not a Armstrong Number.\n" %Number)
Output:
Enter the Number: 370
370 is Armstrong Number
Python Program to find Armstrong Number using recursion:
In this program allows the user to enter any positive integer and then, we will find given number is Armstrong or not using recursion
# Initializing Number of Digits
Sum = 0
Times = 0
# Calculating Number of individual digits
def Count_Of_Digits(Number):
global Times
if(Number > 0):
Times = Times + 1
Count_Of_Digits(Number // 10)
return Times
#End of Count Of Digits Function
# Finding Armstrong Number
def Armstrong_Number(Number, Times):
global Sum
if(Number > 0):
Reminder = Number % 10
Sum = Sum + (Reminder ** Times)
Armstrong_Number(Number //10, Times)
return Sum
#End of Armstrong Function
#User Input
Number = int(input("\n Enter the Number: "))
Times = Count_Of_Digits(Number)
Sum = Armstrong_Number(Number, Times)
if (Number == Sum):
print("\n %d is Armstrong Number.\n" %Number)
else:
print("\n %d is Not a Armstrong Number.\n" %Number)
Output:
Enter the Number: 370
370 is Armstrong Number
No comments:
Post a Comment