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);

}

}

}

//I have an idea like this,please help me in this

0 votes

Best answer

0 votes

Let's start with the definition of Armstrong numbers.

given number base

bis 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.

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

...