Definition
Let's start with the definition of Armstrong numbers.
given number base b is a number that is the sum of its own digits each raised to the power of the number of digits.
...
e.g.:
Note: it works for any length of numbers (number of digits: 1, 2, 3, etc ...). Check the linked site for details.
Issues With Your Code
There are various issue with the code you wrote. Syntax and logic has flows alike. Instead of trying to fix that, I went with a new implementation. See "My Solution" below.
My Solution
Here's my code below. It's commented, so I won't do a detailed rundown. I'll just highlight some points:
- We're assuming decimal, non-negative integral numbers
- No extra effort is made to check if the user enters a valid number
- The code wouldn't work correctly when the unsigned long overflows. No efforts were made to test this. One with more time could do that.
#include <stdbool.h>
#include <stdio.h>
static unsigned char CountNumberOfDigits(unsigned long n)
{
unsigned char count = 1;
while (n >= 10)
{
n /= 10;
count++;
}
return count;
}
// Raise a number (digit) to a given power. Returns: digit ^ power
static unsigned long Pow(unsigned char digit, unsigned char power)
{
unsigned long result = 1;
while (power > 0)
{
result *= digit;
power--;
}
return result;
}
static bool IsArmstrongNumber(unsigned long n)
{
unsigned char length = CountNumberOfDigits(n);
unsigned long sum = 0;
unsigned long number = n; // We keep "n" to have the original and process it in "number"
while (number > 0)
{
unsigned char lastDigit = number % 10;
number /= 10; // We are cutting off the last digit and need to process the remaining number
sum += Pow(lastDigit, length);
}
return n == sum;
}
int main()
{
unsigned long n; // using unsigned long type as we're not interested in negative numbers and to store as large numbers as possible
printf("Enter n: ");
scanf("%lu", &n);
unsigned long i = n + 1;
while (!IsArmstrongNumber(i))
i++;
printf("The smallest Armstrong number greater than %lu is: %lu\n", n, i);
return 0;
}