# Given a value for n find the smallest armstrong number greater than n

+1 vote
include<stdio.h>
main()
{
int n,x,r,sum=0,y;
printf("enter n");
scanf("%d",&n);
for(x=1;x>n;x=x+1)
{
y=x;
r=y%10;
sum=sum+r*r*r;
y=y/10;
if(sum==x)
{
printf("%d",x);
}
}
}

answered Apr 19, 2021 by (440 points)
selected May 18, 2021 by Anitha

#include <stdio.h>

int main()
{
int n,m,temp=1,r,sum;
scanf("%d",&n);
m=n+1;
while(temp>0)
{
sum=0;
temp=m;
while(m>0)
{
r=m%10;
sum=sum+(r*r*r);
m=m/10;
}
if(temp==sum)
{
printf("%d",temp);
break;
}
else
m=temp+1;
}
return 0;
}
answered Apr 12, 2021 by (89,040 points)
edited Apr 13, 2021 by Peter Minarik

# Definition

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.

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;
}```