Check If a Number is Armstrong in Python
An Armstrong number (also known as a narcissistic number) is a number that is equal to the sum of its own digits raised to the power of the number of digits. For instance, a three-digit Armstrong number is a number for which the sum of the cubes of its digits equals the number itself.
Take the number 371. We can verify if it’s an Armstrong number by checking if:33+73+13=3713^3 + 7^3 + 1^3 = 37133+73+13=371
Since the sum of the cubes of 3, 7, and 1 is 371, the number is indeed an Armstrong number.
An Armstrong number of n digits is an integer such that the sum of the nth powers of its digits is equal to the number itself.
For example:
13+53+33=1531^3 + 5^3 + 3^3 = 15313+53+33=153
33+73+13=3713^3 + 7^3 + 1^3 = 37133+73+13=371
To check whether a given number is an Armstrong number, follow this algorithm:
sum = 0
and temp = number
.temp != 0
:temp % 10
.remainder^n
to sum
.temp
by dividing it by 10.sum == number
, display “Armstrong number”.Here’s a simple Python program to check if a given number is an Armstrong number:
# Python program to check Armstrong number
number = int(input("Enter a number: "))
sum = 0
temp = number
n = len(str(number))
while temp != 0:
remainder = temp % 10
sum += remainder ** n
temp //= 10
if sum == number:
print(f"{number} is an Armstrong number")
else:
print(f"{number} is not an Armstrong number")
Here’s an example of how to check if a number is Armstrong using C language:
#include <stdio.h>
#include <math.h>
int main(int argc, char *argv[]) {
int n = atoi(argv[1]);
int sum = 0;
int temp = n;
int cnt = 0;
while(n != 0) {
n = n / 10;
cnt++;
}
n = temp;
while(n != 0) {
int rem = n % 10;
sum = sum + pow(rem, cnt);
n = n / 10;
}
if (temp == sum)
printf("Yes\n");
else
printf("No\n");
return 0;
}
The time complexity of checking whether a number is Armstrong is O(n), where n is the number of digits in the given number. This is because we iterate over each digit once.
Checking whether a number is an Armstrong number is a fun and simple exercise in programming. Whether you’re practicing Python or C, understanding how to break down a number into its digits and apply powers is a useful skill for coding and problem-solving.