How to find a pair of integers closest to perfect square of a number?

595 Views Asked by At

I need to make graphs in a software that are grouped in subplots. For this, I need to specify how many rows and how many columns of plots there will be. However, I do not know the total number of plots there will be.

I am therefore looking for a pseudo-code (or small algorithm) that would allow me to automatically define the number of rows and columns for those subplots.

Here is the objective of the problem:

  • The number of rows and columns should be as close as possible from a perfect square.

Here are the constraints of the objective:

  • The two numbers should be integers
  • The number of rows should be larger than or equal to the number of columns
  • The product of the two numbers should be larger than or equal to the number of subplots

I realize now that the problem resembles the maximization of the area of a four-sided figure with four right angles given its perimeter, with the perimeter being the number of subplots and the rows and columns being the length and width.

I am using Matlab, how would the code look like?

Here is what I have so far, but trying with in=7 and in=10 shows it is not correct:

function [rr,cc]=number_subplots(in)

sqrt_in=sqrt(in);
floor_in=floor(sqrt_in);
ceiling_in=ceil(sqrt_in);

[out]=sort([floor_in ceiling_in],'descend')

rr=out(1);
cc=out(2);
1

There are 1 best solutions below

0
On BEST ANSWER

I figured it out:

function [rr,cc]=number_subplots(in)

sqrt_in=sqrt(in);
floor_in=floor(sqrt_in); % round down to nearest integer
ceiling_in=ceil(sqrt_in); % round up to nearest integer

round_in=round(sqrt_in); % round to nearest integer

if round_in>floor_in % case where sqrt_in is above .5 mark
[out]=sort([round_in round_in],'descend'); % square of ceiling is enough
else
  [out]=sort([round_in round_in+1],'descend'); % floor*ceiling is enough 
end


rr=out(1);
cc=out(2);