Python Program to Check Whether an Integer is Armstrong Number or Not.

 


An Armstrong number is a number that is equal to the sum of its own digits each raised to the power of the number of digits in the number. For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153.

Program Code:

num = int(input("Enter a number: "))
# determine the number of digits in the input number
num_digits = len(str(num))
# initialize the sum of the cube of digits to 0
sum_of_cubes = 0
# iterate over each digit in the input number and add its cube to the sum
for digit in str(num):
sum_of_cubes += int(digit) ** num_digits
# check if the sum of cubes is equal to the original number
if num == sum_of_cubes:
print(num, "is an Armstrong number")
else:
print(num, "is not an Armstrong number")


Program Explanation:

  1. We first take an input integer from the user using the input() function and convert it to an integer using the int() function.
  2. We determine the number of digits in the input number by converting it to a string using the str() function, getting its length using the len() function, and storing the result in the variable num_digits.
  3. We initialize a variable called sum_of_cubes to 0, which will hold the sum of the cubes of each digit in the input number.
  4. We use a for loop to iterate over each digit in the input number. Since the input number is an integer, we first convert it to a string using the str() function so that we can iterate over each of its digits. For each digit, we convert it back to an integer using the int() function, cube it using the ** operator, and add it to sum_of_cubes.
  5. After the loop has finished, we check if num is equal to sum_of_cubes. If it is, then num is an Armstrong number, so we print a message saying so. Otherwise, we print a message saying that num is not an Armstrong number.

Comments

Popular posts from this blog

Pseudocode to Check, Number is Odd or Even

How to Create Marksheet in C

C Program to Calculate Acceleration