How Can We Help?
Introduction
An Armstrong number is a fascinating mathematical concept that can be easily implemented in Python. It is a number that is equal to the sum of its digits raised to the power of the number of digits. In this post, we will explore how to identify Armstrong number in Python, and the significance of this concept in programming. Whether you are a beginner or an experienced programmer, this post will introduce you to the power of mathematics in Python. Let’s get started!
Mathematically it can be expressed as :
abcdef...=an+bn+cn+dn+en+fn+...
For example, 153 can be expressed as
153 = 1*1*1 + 5*5*5 + 3*3*3 .Hence it is an Armstrong number.
But why should we study and learn about these numbers? Well, these numbers have much more things to do in real life. These numbers are not simply found in mathematics for learning; they have a wide range of applications, like the Fibonacci numbers. The Armstrong numbers are widely used in cryptography and data security. Details of how do these numbers used and implemented in cryptography are beyond the scope of this present article.
Armstrong Number Using For Loop
“Check Armstrong Number Using For Loop” is a programming exercise that checks if a given number is an Armstrong number by iterating through each digit of the number using a for loop.
Example (1)
n = int(input("Enter a Number:"))
size = len(str(n))
temp = n
sum = 0
num = str(n)
for i in num:
digit = temp % 10
sum += digit ** size
temp = temp//10
if (sum == n):
print(f"{n} is an Armstrong number")
else:
print(f"{n} is not an Armstrong number")
Output
74 is not an Armstrong number
Armstrong Number Using While Loop
Just like we can use the for loop, we can also implement the previous logic in the while loop too.
Example (2)
num = int(input("Enter a number: "))
sum = 0
size = len(str(n))
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** size
temp //= 10
if (sum == num):
print(f"{num} is an Armstrong number")
else:
print(f"{num} is not an Armstrong number")
Output:
55 is not an Armstrong number
Python Program to Check Armstrong Number Using Function
We can wrap all the logic within functional components to make the code more readable and concise. Both the for loop and the while loop can be used for the implementation.
Example (3)
def check(n):
size = len(str(n))
temp = n
sum = 0
num = str(n)
for i in num:
digit = temp % 10
sum += digit ** size
temp = temp//10
if (sum == n):
return True
else:
return False
def main():
n = int(input("Enter a Number:"))
if (check(n)):
print(f"{n} is an Armstrong number")
else:
print(f"{n} is not an Armstrong number")
if __name__ == '__main__':
main()
Output:
155 is not an Armstrong number
Explanation:
- First, we created a user-defined function named check. The function takes only one argument named n. The function is nonvoid. Under the function, we have defined all the logical codes discussed above in the for loop section.
- We then created another function named the main function. The main function is the driving code of the program. Under this function, we have taken the inputs from the users using the input function.
- We have called the check function to check if the number is Armstrong.
- Finally, we called the main function using the following lines of codes: if __name__ == ‘main‘: main()
We can also implement a while loop as a functional component in the code.
Example (4)
def check(n):
size = len(str(n))
temp = n
sum = 0
num = str(n)
while temp > 0:
digit = temp % 10
sum += digit ** size
temp //= 10
if (sum == n):
return True
else:
return False
def main():
n = int(input("Enter a Number:"))
if (check(n)):
print(f"{n} is an Armstrong number")
else:
print(f"{n} is not an Armstrong number")
if __name__ == '__main__':
main()
Output:
153 is an Armstrong number
Armstrong Number Using Class
Classes are used extensively in productions. This helps to keep the codes more concise. Below is the implementation of class-based implementation to check if a number is an Armstrong number using for loop:
Example (5)
class ArmstrongNumbers:
def __init__(self, n):
self.number = n
def check(self):
size = len(str(self.number))
temp = self.number
sum = 0
num = str(self.number)
while temp > 0:
digit = temp % 10
sum += digit ** size
temp //= 10
if (sum == self.number):
return True
else:
return False
def main():
n = int(input("Enter any number:"))
armstrong = ArmstrongNumbers(n)
if (armstrong.check()):
print(f"{n} is an Armstrong number")
else:
print(f"{n} is not an Armstrong number")
if __name__ == "__main__":
main()
Output:
153 is an Armstrong number
Explanation:
- First, we created a class named ArmstrongNumbers. We defined the constructor using the init method, and the constructor takes only one argument, called n.
- Next, we created a function within the class named check. Under this function, we implemented the logic we discussed earlier. The only difference is that we have accessed the variable from the constructor.
- The function will return true if the number is an Armstrong number and will return false if it is not an Armstrong number.
- Next, we defined the main function. The main function is the driving code of the program. Under this function, we took the inputs from the users using the input function of python.
- Next, we created the Armstrong object named Armstrong. We passed the number as the parameter to the object. We then called the check function within the class to check if the number was an Armstrong number.
- We printed if the number is Armstrong, depending on the print statement’s condition.
Below is the code for class-based implementation to check if a number is an Armstrong number using the for loop:
Example (6)
class ArmstrongNumbers:
def __init__(self, n):
self.number = n
def check(self):
size = len(str(self.number))
temp = self.number
sum = 0
num = str(self.number)
for i in num:
digit = temp % 10
sum += digit ** size
temp = temp//10
if (sum == self.number):
return True
else:
return False
def main():
n = int(input("Enter any number:"))
armstrong = ArmstrongNumbers(n)
if (armstrong.check()):
print(f"{n} is an Armstrong number")
else:
print(f"{n} is not an Armstrong number")
if __name__ == "__main__":
main()
Output:
153 is an Armstrong number
Armstrong Number Using the Power Function
We can tweak many code logics on our own to have similar output. One of the tweaks we can make is the use of the pow function of python to have the power of the number.
Example (7)
num = int(input("Enter a number: "))
sum = 0
size = len(str(num))
temp = num
while temp > 0:
digit = temp % 10
sum += pow(digit,size)
temp //= 10
if (sum == num):
print(f"{num} is an Armstrong number")
else:
print(f"{num} is not an Armstrong number")
Output:
45 is not an Armstrong number
We have written programs to check whether a number is an Armstrong number in python. Using similar techniques, we can also find out the series of Armstrong numbers in python. The below code illustrates the same:
Example (8)
def check(n):
size = len(str(n))
temp = n
sum = 0
num = str(n)
while temp > 0:
digit = temp % 10
sum += digit ** size
temp //= 10
if (sum == n):
return True
else:
return False
def main():
n = int(input("Enter a Number upto which you want to find armstrong numbers:"))
l = []
for i in range(1, n+1):
if (check(i)):
l.append(i)
else:
continue
print(f"The Armstrong numbers are: {l}")
if __name__ == '__main__':
main()
Output:
The Armstrong numbers are: [1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634]
Note(our input here is 2500)
The above method was an implementation using the while loop. However, we can also implement similar logic using the for loop to achieve similar output:
Example (9)
def check(n):
size = len(str(n))
temp = n
sum = 0
num = str(n)
for i in num:
digit = temp % 10
sum += digit ** size
temp = temp//10
if (sum == n):
return True
else:
return False
def main():
n = int(input("Enter a Number upto which you want to find armstrong numbers:"))
l = []
for i in range(1, n+1):
if (check(i)):
l.append(i)
else:
continue
print(f"The Armstrong numbers are: {l}")
if __name__ == '__main__':
main()
Output:
The Armstrong numbers are: [1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634]
Note(our input here is 2500)
We can also implement classes to achieve similar output.
Example (10)
class ArmstrongNumbers:
def __init__(self, n):
self.number = n
def check(self):
size = len(str(self.number))
temp = self.number
sum = 0
num = str(self.number)
for i in num:
digit = temp % 10
sum += digit ** size
temp = temp//10
if (sum == self.number):
return True
else:
return False
def main():
n = int(input("Enter any number:"))
l=[]
for i in range(1,n+1):
armstrong = ArmstrongNumbers(i)
if (armstrong.check()):
l.append(i)
else:
continue
print(f"The Armstrong numbers are: {l}")
if __name__ == "__main__":
main()
Output:
The Armstrong numbers are: [1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634]
Note(our input here is 2500)
Try function-based implementation with a while loop and class-based implementation using the while loop as an exercise.
Armstrong Number Using Tkinter
We can implement the program in a graphical interface too. Instead of giving the input and getting the output in the command line, the users may also desire to do everything in Graphical Interface instead. Python has a great library called Tkinter which we can use to make GUI interfaces in python. The below code will show its usage.
Example (11)
# Import all the necessary libraries and modules in the code
from tkinter import *
# Define a function check to check if a given number is an Armstrong number.
def check(n):
size = len(str(n))
temp = n
sum = 0
num = str(n)
for i in num:
digit = temp % 10
sum += digit ** size
temp = temp//10
if (sum == n):
return True
else:
return False
# Defining the main function
def main():
# Ceating a root object for the window
root = Tk()
# Defining the geometry/size of the window
root.geometry("400x400")
# Labelling the first grid
Label(root, text="Enter the number:").grid(row=0, column=0)
# Defining the label on which we need to display the result
label3 = Label(root)
# Defining the grid position of the result grid.
label3.grid(row=6, column=1)
# Defining the data type of the first grid
num = IntVar()
# Defining the area where the user will enter the number
entry1 = Entry(root, textvariable=num).grid(row=0, column=1)
# Defining the function to print based on whether a number is Armstrong number
def Armstrong():
n = num.get()
if (check(n)):
label3.config(text="your final number is Armstrong number")
else:
label3.config(text="your final number is not Armstrong number.")
# Defining the button
mybutton = Button(root, text=("Check"),
command=Armstrong).grid(row=4, column=1)
# Looping and wrapping up all the logical code for the window
root.mainloop()
# Calling the main function
if __name__ == "__main__":
main()
Output:
Conclusion
This article taught us how to check Armstrong numbers using different implementation types. We used the for and the while loops to check whether a number is an Armstrong number. We implemented the methods both in function as well as classes. We also learned how to get the series of Armstrong numbers printed in python using similar logic.
We have given a few exercises to the readers within the article. We expect the readers to solve those exercises to understand the topic better. Feel free to post your doubts regarding the concept in the Oraask forum.