Array of section 2d in subarrays

I need to split a 2d array (size specified by user) into subarrays specified by user by user. The code I wrote works well for most instances, there are some of them that I need help about.

I do this by taking the square root of the input number. So, for example: If the user inserts [10, 10, 9], this means that it is a 10 * 10 array with 9 subarrays. Taking the square root of 9 works fine because it gives 3. If the user inserts [8, 6, 6], he takes the square root of 6 and rounds it to the longest side (which gives 3) and rounds it for the shortest (which equals 2). So 3 * 2 = 6. It also works great.

Then a situation such as 8. arises. The square root of 8 gives 3 and 2. Thus, the array is divided into 6 subarrays. Is there any other way to find a better breakdown into numbers like 8, 14? Or is there a way to find the optimal distribution for such numbers (for example, 2 * 4 = 8, 2 * 7 = 14)?

+4
source share
2 answers

You can calculate them a little differently:

int x = Math.round(Math.sqrt(n));
int y = Math.round(1. * n / x);

Thus you will receive:

n = 8  => x = 3, y = 3
n = 14 => x = 4, y = 4
+1
source

What you need to do is find the two closest factors to the square root. Try this code:

long n = 14;

long y = 0;
long x = Math.round(Math.sqrt(n));
while(true){
    if (n % x == 0) {
        y = n/x;
        break;
    }
    else {
        x--;
    }
}

You may also need some error checking to deal with input errors. e.g. n <1.

0
source

All Articles