Alberto Rossi
Alberto Rossi

Reputation: 1800

Simplify a square root

Let's say that I want to calculate the square root of 8. There are two ways to display the result as you can see here:

enter image description here

I think that the best way I have to obtain the second solution is this:

enter image description here

I want to try do display in my Java application 2√2 instead of 2,828427... and so I thought to develop a class following these steps. Let's consider the square root of 8.

  1. Get the prime factors of 8 (2*2*2)
  2. Count the exponent and try to export them (2^2 * 2 --> 2√2)

I have developed, as you can see below, a code that outputs the factors. If you input 8, the method estraiRadice() will output 2 * 2 * 2, which is correct.

private int b = 2;

public String estraiRadice(double x) {

  String resRad = "";
  int[] exponents = new int[100];

  //Scomposizione in fattori primi
  while (x > 1) {

    if ((x % b) == 0) {
      x /= b;
      resRad += String.valueOf(b) + " * ";
    } else {
      b++;
    }
  }

  return resRad;
}

The second step is giving me problems because I don't know exactly how to do create the power of a number and export it from the square root. I mean: how can that √2*2*2 become a √4*2 and then 2√2?

I thought that I could store in an array the exponent for each base and then try to export it somehow. Do you have any advice?

Upvotes: 5

Views: 1573

Answers (2)

Sam
Sam

Reputation: 381

Try this:

public static int[] squareRoot(int number) {
    int number1 = number;
    List<Integer> roots = new ArrayList<>();
    int coefficient = 1;
    for (int i = 2; i < number1; i++) {
        if (number1 % (i * i) == 0) {
            roots.add(i);
            number1 /= i * i;
            for (int j = 2; j < number1; j++) {
                if (number1 % (j * j) == 0) {
                    roots.add(j);
                    number1 /= j * j;
                }
            }
        }
    }
    for (int root : roots) coefficient *= root;
    return new int[]{coefficient, number1};
}

You can call it like this:

System.out.println(squareRoot(96)[0] + "√" + squareRoot(96)[1]);

Upvotes: 2

Erman Turan
Erman Turan

Reputation: 96

You can use a HashMap to store prime number power pairs

HashMap<Integer,Integer> getRoots(int x)
{

    HashMap<Integer,Integer> retval = new HashMap<Integer,Integer>();
    int i=2;

    while(i<=x)
    {
        int power = 0;

        while( x%i == 0)
        {
            power++;
            x /= i;
        }

        if(power>0)
        {
            retval.put(i,power);
        }

        if(x==1)
        {
            break;
        }

        i++;
    }

    return retval; 
}

Upvotes: 1

Related Questions