To find whetever a number is armstrong or not. Find the mistake in my code

#include <bits/stdc++.h>

using namespace std;

int main()

{

int N;

cout << "N: " ;

cin >> N;

int sum=0;

int M=N ;

while (N>0)

{

    int last = N % 10 ;

    N = N%10;

    sum = sum + pow(last, 3) ;

}

if(sum = M )

{

    cout << "it's an armstrong" ;

} 

else {

    cout << "no"; 

}

return 0;

}

    int last = N % 10 ;
    N = N%10;
    sum = sum + pow(last, 3) ;

Do you mean N=N/10 in the 2nd line? (or do you mean to just process the last digit twice instead of all digits once?)

Why are you raising everything to power 3? Do you want to raise to power number of digits?

1 Like

yepp I got it, I wanted the last digit of N , so instead of % in should be /
thanks

but still after changing % to / in 2nd line, it’s showing that every number is a armstrong.
WHY?

if(sum = M )
{

Compiler warnings, dude :slight_smile:

3 Likes

Please go slowly and refer 2nd part of my comment

Why are you raising everything to power 3? Do you want to raise to power number of digits?

That’s not how you compare 2 variables

2 Likes

I got (sum == M) part,
I want to cube all the digits of the number and add them, if the sum = number then it’s an armstrong.
but after changing the Sum==M part, I checked for number 153 which is an armstrong but code is saying it’s not.

I copied your code and tested on my machine. It does say it’s armstrong

#include <bits/stdc++.h>
using namespace std;

int main()
{
int N;
cout << "N: " ;
cin >> N;
int sum=0;
int M=N ;
while (N>0)
{
    int last = N % 10 ;
    N = N/10;
    sum = sum + pow(last, 3) ;
}
if(sum == M )
{
    cout << "it's an armstrong" ;
} 
else {
    cout << "no"; 
}
return 0;
}

what is it ?

sorry bro for the inconvenience, I got that right now

1 Like