Question

Please have a look at the following code

#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int main()
{
    //int side1 = 0;
    //int side2 = 0;
    //int rightSide = 0;

    cout << "Right Side" << setw(10) << "Side1" << setw(10) << "Side2" << endl;

    for(int i=1;i<=500;i++)
    {
        //side1++;
        //cout << side1 << endl;

        for(int a=1;a<=500;a++)
        {
            //side2++;
            //cout << "side 2 " << side2 << endl;

            for(int c=1;c<=500;c++)
            {
                //rightSide++;
                int rightSideSqr = pow(c,c);
                int side1Sqr = pow(i,i);
                int side2Sqr = pow(a,a);

                if(rightSideSqr == (side1Sqr+side2Sqr))
                {
                    cout << rightSideSqr << setw(15) << i << setw(10) << a << endl;
                 }


            }
        }
    }
}

This gives an error "PythagorialTriples.cpp:28: error: call of overloaded `pow(int&, int&)' is ambiguous". This doesn't happen if I simply used manual power like i*i, instead of the method. Can someone please explain me why this is happening? I am new to C++ anyway. Thanks

Was it helpful?

Solution

There are multiple overloads for pow defined in <cmath>. In your code, these 3 are all equally valid, therefore the compiler is having trouble choosing the right one:

        pow(float, int);
        pow(double, int);
        pow(long double, int);

The simplest solution is to use static_cast on the first argument, to remove any ambiguity. e.g.

int side1Sqr = pow( static_cast<double>(i) ,i );
int side2Sqr = pow( static_cast<double>(a) ,a );

OTHER TIPS

Whoa! Pow(x,y) is x raised to the yth power (in mathematical terms - xy)!! NOT x*y

So you're trying to take iith power in a 5003 nested loop. Probably not what you want. Replace with pow(i,2) for your desired behavior.

Note, @Mooing Duck raises an excellent point about x^y in c++ which is the XOR operator. But I think you sort of figured that out if you're already using pow anyway.

It cannot figure out which overloaded function to use. Try

pow(double(i), i);

or

pow(double(i), 2);

Since that looks like what you want.

Are you sure that you can handle such a big pow?

Pow(x,y) is xy. Look at the

http://www.cplusplus.com/reference/clibrary/cmath/pow/

double pow ( double base, double exponent );

long double pow ( long double base, long double exponent );

float pow ( float base, float exponent );

double pow ( double base, int exponent );

long double pow ( long double base, int exponent );

There is no INT version. Your compiler didnt know which one is correct. You have to tell them by using static_cast like:

int side1Sqr = pow(static_cast<double>i,i);

for big precision calculate you can use:

http://gmplib.org/

There is also one solution from boost.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top