0
 #include<bits/stdc++.h>
using namespace std;
#define ll long long int
bool check(ll num)
{
    ll temp=num;
    ll sum=0;
    while(num!=0)
    {
        ll rem=num%10;
        sum+=pow(rem,3);
        num/=10;
    }
    if(sum==temp)
        return true;
    else
        return false;
}
int main()
{
    ll num;
   cin>>num;
    if(check(num))
        cout<<"It is a Armstrong number"<<endl;
    else
        cout<<"Not a Armstrong number"<<endl;
    return 0;
}

when num is equal to 153 in the second iteration the value of rem is 5 but when im putting that in pow function it is giving me 124 but 5 pow 3 is equal to 125 can anyone tell me whats the issue

2 Answers2

2

The pow function operates on floating-point types, not integers, and it returns a floating-point type. You are seeing the results of integer truncation combined with floating-point error. Consider computing integer powers via integer-based methods, or if you must use std::pow then round the result with std::round.

For example:

sum += static_cast<ll>(std::round(std::pow(rem, 5)));

Alternatively something as naive as:

sum += rem * rem * rem * rem * rem;
paddy
  • 60,864
  • 6
  • 61
  • 103
0

Because you're not using standard include headers, I can't guarantee that you're using one of the overloads of std::pow from <cmath>, some of which take integral types for the exponent. (You could be using the C-style pow which has no overloads).

Your use of using namespace std; further confuses things. Although used in tutorials for clarity, it's never used in good quality production code.

In my opinion, any implementation of std::pow that does not recover the best floating point value with integral arguments ought to be considered defective. That said, no standard I'm aware of (even IEEE754) offers any such guarantees. (Cf. std::sqrt.) You could find that your implementation evaluations pow(x, y) as exp(y * log(x)) and that can cause the result to undershoot the true value for seemingly trivial values of x and y.

For a small exponent like 3, it's best to write it out long hand:

sum += rem * rem * rem;

If you are indeed cursed with a platform that has a defective std::pow implementation, then you can always roll your own for integral arguments. Exponentiation by squaring is frequently the technique used.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483