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)
private static long Power(int x, int y)
{
long p = 1;
for (int i = 1; i <= y; ++i)
{
p *= x;
}
return p;
}
public static bool IsArmstrong(long num)
{
long sum = 0;
int remainder;
int digits = 0;
long temp = num;
while (temp != 0)
{
++digits;
temp /= 10;
}
temp = num;
while (temp != 0)
{
remainder = (int)(temp % 10);
sum += Power(remainder, digits);
temp /= 10;
}
return num == sum;
}
Example
bool isArmstrong = IsArmstrong(371);
Output
true