Is Armstrong Number
This algorithm checks whether a given number is armstrong or not. Armstrong number is a number which is equal to sum of digits raise to the power total number of digits in the number.
Some examples of armstrong numbers are:
7 = 7^1
371 = 3^3 + 7^3 + 1^3 (27 + 343 +1)
8208 = 8^4 + 2^4 +0^4 + 8^4 (4096 + 16 + 0 + 4096)
/*****Please include following header files*****/
// stdint.h
// stdbool.h
/***********************************************/
int64_t Power(int base, int exp) {
int64_t p = 1;
for (int i = 1; i <= exp; ++i) {
p *= base;
}
return p;
}
bool IsArmstrong(int64_t num) {
int64_t sum = 0;
int remainder;
int digits = 0;
int64_t temp = num;
while (temp != 0) {
++digits;
temp /= 10;
}
temp = num;
while (temp != 0) {
remainder = temp % 10;
sum += Power(remainder, digits);
temp /= 10;
}
return num == sum;
}
Example
bool isArmstrong = IsArmstrong(371);
Output
true