Skip to content
Advertisement

how do i find the values of A,B and C in java

given the following values X,Y,Z, such as (0≤X,Y,Z≤10000) with considering the following three equations :

  1. a+b+c = X
  2. abc = Y
  3. a^2 + b^2+ c^2 = Z

i need to find values of a, b and c, I wrote something like this in java:

    for (int a = 0 ; x<= num; x++){
        for(int b =0 ; y<=num; y++){
            for(int c=0 ; z<=num; z++){
                int power = (int) Math.pow(a,2) + (int) Math.pow(b,2)+ (int) Math.pow(c,2); 
                if((x+y+z == X) && (x*y*z==Y) && (power==Z)){
                    System.out.println(a+" "+b+" "+c);
                    System.exit(0);
                }
                
            }
        }
    }
    
    System.out.println("no values found");

but its a naïve solution because the values of a,b and c can be zero, positive or negative numbers and must be distinct (a≠b≠c).

for example:

  • input: 6 6 14 – output: 1 2 3
  • input: 1 2 3 – output : no values found

input represent x,y,z and output represent a,b,c. can someone please put me on the right path and help me.

Advertisement

Answer

If you don’t want (or can) solve it analitically and the solutions are guaranteed to be integers (or you’re only looking for integer solutions) then this code will work and also handle negative numbers:

package test;

import java.util.Scanner;

public class TestIntEquation {
    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        
        long X=in.nextLong();
        long Y=in.nextLong();
        long Z=in.nextLong();

        int[] sign= {1,-1};
        
        for (long a=0;a*a<=Z;a++) {
            for (long b=0;a*a+b*b<=Z;b++) {
                long c=(long) Math.sqrt(Z-a*a-b*b);
                if (a*a+b*b+c*c!=Z) continue;
                long mul=a*b*c;
                if (mul!=Math.abs(Y)) continue;
                for (int signA: sign) {
                    for (int signB: sign) {
                        for (int signC: sign) {
                            if (signA*a==signB*b||signA*a==signC*c||signB*b==signC*c) continue;
                            long sum=signA*a+signB*b+signC*c;
                            mul=signA*a*signB*b*signC*c;
                            if (sum==X&&mul==Y) {
                                System.out.println(a*signA+" "+b*signB+" "+c*signC);
                                return;
                            }
                        }
                    }
                }
            }
        }
        System.out.println("no values found");
    }
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement