[SOLVED] Program works for one true case, but not for other – Stack Overflow

Issue

This Content is from Stack Overflow. Question asked by Lakshay Malik

So, I wrote this program to check if a given number is an armstrong number or not. But when I ran this code with 153 as input (an armstrong) it shows “not armstrong”, but when I ran it for other numbers like 370, 371 (armstrong numbers) it shows “Armstrong”. Even more, when I ran it with an online compiler, it ran completely fine but on my laptop (using MinGW) it shows the error with 153. Here is the code (I have included the math.h file):

int n;
cin>>n;

int sum=0;
int originaln=n;
while(n>0){
    int lastdigit=n%10;
    sum+= pow(lastdigit,3);
    n=n/10;
}
if(sum==originaln){
    cout<<"Armstrong"<<endl;
}
else{
    cout<<"Not Armstrong"<<endl;
}
return 0;

Also, can someone tell why this code doesn’t work for 4 digit numbers?



Solution

The code doesn’t work for 4 digits because while updating the "sum" you are not taking care of the number of digits in the number

For example for a 4-digit number it should be:

 sum+= pow(lastdigit,4);

In order to create a standard approach, you can check for the number of digits in the number and then update the value for ‘n’ digits in a number

You can refer to this website for the approach: Source

Coming to the test case for number: 153, the code works fine and provides the correct output

Check if you have correctly included the header file

You can run your code through an online compiler and check for yourself: Source


This Question was asked in StackOverflow by Lakshay Malik and Answered by Sprivro It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?