How to check if a number multiplies to something but adds to something

761 Views Asked by At

So I've been trying to make some sort of a calculator tool. One of the function is to check if a factor of a number multiplies to something but at the same time adds to something else. This is helpful for factoring a trinomial. I found the factors but I don't know how to proceed. This is what I have so far

public static void MA() {
     int sum = 0;
     int product = 0;
     ArrayList<Integer> Factors = new ArrayList<Integer>();

     
     
     System.out.println("Enter the sum of the number");
     sum = sc.nextInt();
     System.out.println("Enter the number it should multiply to");
     product = sc.nextInt();

if(product < 0){
  for(int i = product; i <= Math.abs(product); ++i) {

      // skips the iteration for i = 0
      if(i == 0) {
        continue;
      }
      else {
        if (product % i == 0) {
          Factors.add(i);
        }
}
    }
  }
  else{
    for (int i = 1; i <= product; ++i) {
  
      // if number is divided by i
      // i is the factor
      if (product % i == 0) {
        Factors.add(i);
      }
    }
  }  

  System.out.println(Factors);
   }

Keep in mind the architecture of my program is a main class that calls on all other functions.

EXAMPLE: X^2 + 9x + 20 = (x+5)(x+4)

4*5 = 20 4+5 = 9

1

There are 1 best solutions below

0
On

Your problem can be succinctly expressed as follows:

Given a List<Integer>, find 2 of its elements that sum to a given number.

A simple solution to which is:

List<Integer> factors = new ArrayList<>(); // populated elsewhere
int sum = ?; // whatever
Integer a = null;
Integer b = null;

outer:
for (int i = 0; i < factors.size() - 1; i++) {
    for (int j = i + 1; j < factors.size(); j++) {
        if (factors.get(i) + factors.get(j) == sum) {
            a = factors.get(i);
            b = factors.get(j);
            break outer;
        }
    }
}

If a and b are not null, a pair that summed to sum was found.