nobalG
nobalG

Reputation: 4620

Problem determining if a number is an Armstrong Number

I'm trying to check whether or not the number provided by the user is an armstrong number. Something is wrong though and I can't figure it out.

Any help is appreciated.

Code attached below.

#include<stdio.h>

int fun(int);

int main()
{
    int x,a,b,y=0;

    printf("enter the number you want to identify is aN ARMSTRONG OR NOT:");
    scanf("%d",&a);

    for(int i=1 ; i<=3 ; i++)
    {
        b = a % 10;
        x = fun(b);
        y = x+y;
        a = a/10;
    }

    if(y==a)
        printf("\narmstrong number");
    else
        printf("\nnot an armstrong number");

    return 0;
}

int fun(int x)
{
    int a;
    a=x*x*x;
    return (a);
}

Upvotes: 3

Views: 3818

Answers (9)

S M Fazaluddin
S M Fazaluddin

Reputation: 36

Okay so, the thing is that there are also Armstrong numbers that are not just 3 digits for example 1634, 8208 are 4 digit Armstrong numbers, 54748, 92727, 93084 are 5 digit Armstrong numbers and so on. so to check the number is Armstrong or not, here's what I did.

#include <stdio.h>

int main()
{
    int a,b,c,i=0,sum=0;

    printf("Enter the number to check is an Armstrong number or not :");
    scanf("%d",&a);
    
    //checking the digits of the number.
    b=a;
    while(b!=0)
    {
        b=b/10;
        i++;
    }
    // i indicates the digits

    b=a;
    while(a!=0)
    {
        int pwr = 1;
        c= a%10;

        //taking mod to get unit place and getting its nth power of their digits    

        for(int j=0; j<i; j++)
        {
            pwr = pwr*c;
        }

        //Adding the nth power of the unit place

        sum += pwr;
        a = a/10;
        //Dividing the number to give the end condition
    }

    if(sum==b)
    {
        printf("The number %d is an Armstrong number",b);
    }
    else
    {
        printf("The number %d is not an Armstrong number",b);
    }
}

Upvotes: 1

Prossenjit Chanda
Prossenjit Chanda

Reputation: 1

This is the most simplest code i have made and seen ever for Armstrong number detection:

def is_Armstrong(y):
    if y == 0:
        print('this is 0')
    else:
        x = str(y)
        i = 0
        num = 0
        while i<len(x):
            num += int(x[i])**(len(x))
            i += 1
            if num == y:
                print('{} is an Armstrong number.'.format(num))
                break
            else:
                print('{} is not an Armstrong number.'. format(y))
is_Armstrong(1634)

Upvotes: -1

Shehreen Khan
Shehreen Khan

Reputation: 75

Here's a way to check whether a number is armstrong or not

t=int(input("nos of test cases"))
while t>0:
    num=int(input("enter any number = "))
    n=num
    sum=0
    while n>0:
        digit=n%10
        sum += digit ** 3
        n=n//10

    if num==sum:
        print("armstronng num")
    else:
        print("not armstrong")
    t-=1

Upvotes: 0

grepit
grepit

Reputation: 22392

If you are trying to find a armstrong number the solution you posted is missing a case where your digits are great than 3 ...armstrong numbers can be greater than 3 digits (for example 9474). Here is the code in Python, the logic is simple and it can be converted to any other language.

def check_armstrong(number):
    num = str(number)
    total=0
    for n in range(len(num)):
        total+=sum(int(num[n]),len(num))       

    if (number == total):
        print("we have armstrong #",total)

def sum(input,power):
    input = input**power
    return input

check_armstrong(9474)

Upvotes: 0

Renish Patel
Renish Patel

Reputation: 688

Check No. is Armstrong or Not using C Language

#include<stdio.h>
#include<conio.h>
void main()
{
    A:
    int n,n1,rem,ans;
    clrscr();
    printf("\nEnter No. :: ");
    scanf("%d",&n);

    n1=n;
    ans=0;
    while(n>0)
    {
        rem=n%10;
        ans=ans+(rem*rem*rem);
        n=n/10;
    }

    if(n1==ans)
    {
        printf("\n Your Entered No. is Armstrong...");
    }
    else
    {
        printf("\n Your Entered No. is not Armstrong...");
    }

    printf("\n\nPress 0 to Continue...");
    if(getch()=='0')
    {
        goto A;
    }
    printf("\n\n\tThank You...");
    getch();
}

Upvotes: 0

Rakesh Kusuma
Rakesh Kusuma

Reputation: 91

/* 
Name: Rakesh Kusuma

Email Id:  [email protected]

Title: Program to Display List of Armstrong Numbers in 'C' Language

*/



#include<stdio.h>

#include<math.h>

int main()

{

int temp,rem, val,max,temp1,count;

int num;

val=0;

num=1;

printf("What is the maximum limit of Armstrong Number Required: ");

scanf("%d",&max);

printf("\nSo the list of Armstrong Numbers Before the number %d are: \n",max);

while(num <=max)

    {         
        count = 0;

        temp1 = num;

        while(temp1!=0)

        {
            temp1=temp1/10;

            count++;
        }   

        if(count<3)

        count = 3;

            temp = num;

            val = 0;

            while(temp>0)

            {

                rem = temp%10;

                val = val+pow(rem,count);

                temp = temp/10;

            }

            if(val==num)

            {

                printf("\n%d", num);

            }

     num++; 

    }

 return 0;

 }

Upvotes: 0

Johan
Johan

Reputation: 76670

#include<stdio.h>
#include <math.h>

int power(int, int);
int numberofdigits(int);

//Routine to test if input is an armstrong number.
//See: http://en.wikipedia.org/wiki/Narcissistic_number if you don't know
//what that is. 

int main()
{
    int input;
    int digit;
    int sumofdigits = 0;

    printf("enter the number you want to identify as an Armstrong or not:");
    scanf("%d",&input);

    int candidate = input;
    int digitcount = numberofdigits(input);

    for(int i=1 ; i <= digitcount ; i++) 
    {
        digit = candidate % 10;
        sumofdigits = sumofdigits + power(digit, digitcount);
        candidate = candidate / 10;
    }

    if(sumofdigits == input)
        printf("\n %d is an Armstrong number", input);
    else
        printf("\n %d is NOT an Armstrong number", input);
    return 0;
}

int numberofdigits(int n);
{
  return log10(n) + 1;
}

int power(int n, int pow)
{
  int result = n;
  int i=1;
  while (i < pow) 
  {
    result = result * n; 
    i++;
  }
}

What was wrong with the code:

  1. No use of meaningful variable names, making the meaning of the code hard to understand; remember code is written for humans, not compilers.
  2. Don't use confusing code this code: int x,a,b,y=0; is confusing, do all vars get set to 0 or just y. Always put vars that get initialized on a separate line. It makes reading easier. Go the extra mile to be unambiguous, it will pay off big time in the long run.
  3. Use comments: If you don't know what an armstrong number is, than it will be very hard to tell from your code. Put a few meaningful comments in so people know what your code it supposed to do. This will make it easier for you and others because they know what you meant to do and can see what you actually did and solve the difference if need be.
  4. use meaningful routine names WTF does fun(x) do?. Never name anything fun() it's like fact free science, what's the point?
  5. Don't hardcode things, your routine only accepted armstrong3 numbers, but if you can hardcode then why not do return (input == 153) || (input == 370) || ....

Upvotes: 2

Jonathan Leffler
Jonathan Leffler

Reputation: 754440

The primary problem is that you don't keep a record of the number you start out with. You divide a by 10 repeatedly (it ends as 0), and then compare 0 with 153. These are not equal.

Your other problem is that you can't look for 4-digit or longer Armstrong numbers, nor for 1-digit ones other than 1. Your function fun() would be better named cube(); in my code below, it is renamed power() because it is generalized to handle N-digit numbers.


I decided that for the range of powers under consideration, there was no need to go with a more complex algorithm for power() - one that divides by two etc. There would be a saving on 6-10 digit numbers, but you couldn't measure it in this context. If compiled with -DDEBUG, it includes diagnostic printing - which was used to reassure me my code was working right. Also note that the answer echoes the input; this is a basic technique for ensuring that you are getting the right behaviour. And I've wrapped the code up into a function to test whether a number is an Armstrong number, which is called iteratively from the main program. This makes it easier to test. I've added checks to the scanf() to head off problems, another important basic programming technique.

I've checked for most of the Armstrong numbers up to 146511208 and it seems correct. The pair 370 and 371 are intriguing.

#include <stdio.h>
#include <stdbool.h>

#ifndef DEBUG
#define DEBUG 0
#endif

static int power(int x, int n)
{
    int r = 1;
    int c = n;
    while (c-- > 0)
        r *= x;
    if (DEBUG) printf("    %d**%d = %d\n", x, n, r);
    return r;
}

static bool isArmstrongNumber(int n)
{
    int y = 0;
    int a = n;
    int p;
    for (p = 0; a != 0; a /= 10, p++)
        ;
    if (DEBUG) printf("    n = %d, p = %d\n", n, p);
    a = n;
    for (int i = 0; i < p; i++)
    {
        y += power(a % 10, p);
        a /= 10;
    }
    return(y == n);
}

int main(void)
{
    while (1)
    {
        int a;
        printf("Enter the number you want to identify as an Armstrong number or not: ");
        if (scanf("%d", &a) != 1 || a <= 0)
            break;
        else if (isArmstrongNumber(a))
            printf("%d is an Armstrong number\n", a);
        else
            printf("%d is not an Armstrong number\n", a);
    }

    return 0;
}

Upvotes: 3

cnicutar
cnicutar

Reputation: 182664

One problem might be that you're changing a (so it will no longer have the original value). Also it would only match 1, 153, 370, 371, 407. That's a hint to replace the for and test until a is zero and to change the function to raise to the number of digits.

Upvotes: 2

Related Questions