Search code examples
calgorithmnumbersnumber-theory

Error in C program to find integer triplets (x,y,z) such that n^x + n^y = n^z for given range of n


I want to make a C program compatible for DEV-C++ 4.9.9.2 to find integer triplets (x,y,z) such that for any integer n the equation n^x + n^y = n^z holds where n is any integer in the range [a,b]. The c program would have an input of only a and b and find such possible triplets.

The code that I wrote isn't working. What's the error in it?

for (n = a ; n <= b ; n++) {
    for (x = a ; x < b ; x++) {
        for (y = a ; y < b ; y++) {
            for (z = a ; z = b ; z++) {
                c = pow(n, x); 
                d = pow(n, y);
                e = pow(n, z);
                f = c + d;
                if (e = f) {
                    printf("(%d , %d , %d) : %d", x,y,z,n);
                }
            }
        }
    }
}

I'm a novice in C.


Solution

  • C correction

    Try changing

    if (e=f)
    

    into

    if (e==f)
    

    The first does assignment, the second tests equality.

    (Note that you may also get overflow if the numbers tested get larger than your datatype.)

    Maths approach

    If y==x, then:

    n^x + n^x = n^z
    2n^x =  n^z
    => n == 0 or n == 2 
    

    Now, assume y>x and n!=0.

     n^x + n^y = n^z
     n^x ( 1 + n^(y-x)) = n^z
     => 1+n^(y-x) = n^(z-x)
     => 1 = 0 ( modulo n)
     => impossible unless n==0 (in which case any x,y works) or n==1 (which does not work)
    

    So this equation has solutions for any x,y if n==0. Otherwise, the only solutions are with n==2, x==y and z=x+1.