Categories
Python

Armstrong Numbers

 What are Armstrong Numbers?

The numbers in which the sum of the digits raised to the power of the number of digits is equal to the number itself are called Armstrong numbers. All the programs on Armstrong numbers that I’ve seen to date only work on the specific number of digits. Like they won’t work for an indefinite number of digits. So my approach is to write a program that works on any input. However, you can customize it according to your needs.

This Code is Written in Python 3!

A positive integer is called an Armstrong number of order n if

abcd….. = an + bn + c+ dn……. 

In the case of an Armstrong number of 3 digits, the sum of cubes of each digit is equal to the number itself.

There are four 3 digits Armstrong numbers 153, 370, 371, 407.

For example:  153 = 13 + 53 + 33

Similarly, 370 = 33 + 73 + 03

To Check if a number is Armstrong or not, we’ll first take input from user as

num = input("Enter a number: ")

*Note that we took input as string.

Now that we have input stored in variable num, we’ll create another variable to store the sum of numbers. Let’s name it sum. So,

sum = 0

Now if we modify our original variable num, we won’t have any real input from the user to check the output. So we will create another variable and store the value of  ‘num’ in it. We will perform operations on this temp variable.

temp = int(num)

Now we will initialize a while loop while loop which will work till the number becomes 0.

while temp > 0:

Now we’ll extract each digit in the digit variable as

digit = temp % 10

After extracting each digit we’ll raise it to power of number of digits and then adding it in sum variable.

sum += digit ** len(num)

*len() only works with string values.

After taking the sum, we’ll remove the last digit from the number.

temp = temp//10

All this will continue till the number becomes 0, after it becomes 0, while loop will break and the final result will be stored in ‘sum’.

We’ll use this sum to verify the user input using the if statement. If it returns True, we’ll print “Number is Armstrong”, if not, we will print “Number is not Armstrong”

Complete Code

Advertisements

By Suyash Agarwal

Entrepreneur | Blogger | Programmer
I help people learn how to code and scale business with content marketing.
Check out my AI Writing SaaS - https://flackedai.com