codescracker


python

Python Program to Generate Armstrong Numbers



« Previous Program Next Program »


Generate Armstrong Numbers in Python

To generate armstrong numbers in python, you have to ask from user to enter the interval or simply enter starting and ending number to generate armstrong numbers in between the interval given by the user as shown in the program given below.

An armstrong number can be defined as it is an integer such as the sum of cubes of its digits is equal to the number itself.

Or you can say that an armstrong number is equal to sum of cubes of its digit, for example, if a number is of three digit say abc, then if and only if a3 + b3 + c3 is equal to the number itself, then you can easily say that this number is an armstrong number. For example, let's suppose a number, that is 153 and you have to check whether it is an armstrong number or not, then if 13 + 53 + 33 will be equal to 153, then it is an armstrong number otherwise it isn't an armstrong number.

Let's see the following table to understand about it in a better way:

An integer Checking Armstrong or Not
1 13 = 1 Armstrong
2 23 = 8 Not
134 13 + 33 + 43 = 1+27+64 = 92 Not
153 13 + 53 + 33 = 1+125+27 = 153 Armstrong
371 33 + 73 + 13 = 27+343+1 = 371 Armstrong

Python Programming Code to Generate Armstrong Numbers

Following python program ask from user to enter interval to generate and print armstrong numbers between the interval entered by the user:

# Python Program - Generate Armstrong Numbers

print("Enter 'x' for exit.");
print("Enter the interval (starting and ending number): ");
start = input();
if start == 'x':
    exit();
else:
    end = input();
    lower = int(start);
    upper = int(end);
    for num in range(lower, upper+1):
        tot = 0;
        temp = num;
        while temp != 0:
            dig = temp % 10;
            tot += dig ** 3;
            temp //= 10;
        if num == tot:
            print(num);

Here is the sample run of the above python program to illustrate how to generate armstrong numbers:

generate armstrong numbers python

As you can see from the above output, you have only to enter starting and ending number or interval into which you want to print all the armstrong numbers.

Now let's enter an interval as 1 - 100 and press enter to find out all the armstrong number:

print armstrong number python

Here is the same program on python shell:

python generate armstrong numbers

Program Video with Compile and Run

Same Program in Other Languages

You may also like to learn or practice the same program in other popular programming languages:


« Previous Program Next Program »








Tools
Calculator

Quick Links
Signup - Login - Give Online Test