Write a program to Find Armstrong Number in an Interval in Python
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | # Program to check Armstrong numbers in certain interval # To take input from the user lower = int(input("Enter lower range: ")) upper = int(input("Enter upper range: ")) for num in range(lower, upper + 1): # order of number order = len(str(num)) # initialize sum sum = 0 # find the sum of the cube of each digit temp = num while temp > 0: digit = temp % 10 sum += digit ** order temp //= 10 if num == sum: print(num) |
This is a Python program that checks for Armstrong numbers within a certain range specified by the user. An Armstrong number is a number that is equal to the sum of the cubes of its own digits.
First, the program takes input from the user for the lower and upper range of numbers to check for Armstrong numbers. The input is in the form of strings, so they are cast to integers using the int() function.
Then, the program uses a for loop to iterate through the range of numbers from the lower range to the upper range, inclusive.
The program then calculates the order of the number, which is the number of digits in the number. This is done by converting the number to a string and then finding the length of the string.
A variable “sum” is initialized to zero and then inside the for loop, the program uses a while loop to iterate through the digits of the number. The program uses the modulus operator ( % ) to find the last digit of the number and the integer division operator ( // ) to remove the last digit from the number after each iteration.
The program then raises the last digit to the power of the order of the number and adds it to the “sum” variable.
After the while loop, the program checks if the number is equal to the sum of the cubes of its own digits. If it is, the program prints the number as an Armstrong number.
Overall, this program takes input from the user to specify a range of numbers to check for Armstrong numbers, and then uses a for loop to iterate through the range, a while loop to iterate through the digits of the number and check if it is an Armstrong number, and print the number if it is.