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

334 views Asked by At

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.

3

There are 3 answers

0
Peter de Rivaz On BEST ANSWER

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.

0
Ayushi Jha On

Change

  if (e = f) 

to

  if (e == f) 

The first one assigns f to e, enable compiler warnings for such mistakes. The second one equates the LHS to the RHS.

Secondly, assuming your program is a brute force, i.e., loops for all values of x, y and z, you might want to change this statement:

 for (z = a ; z = b ; z++) 

to

 for (z = a ; z < b ; z++) 
0
pola sai ram On

Your implementation is O(n^4) , actually it can be done in O(n^3) .Here is the code

for (n = a ; n <= b ; n++) {
for (x = a ; x < b ; x++) {
    for (y = a ; y < b ; y++) {
         {
            c = pow(n, x); 
            d = pow(n, y);

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