2
\$\begingroup\$

This question already has an answer here:

Introduction

The task is simple. When given a number, output the most logical rectangle. To explain what a logical rectangle is, I provided some examples:

Input: 24.

All possible rectangles have the form A x B, (A and B are both positive integers). So, all possible rectangles for 24 are:

  • 1 x 24
  • 2 x 12
  • 4 x 6

From this list, the most logical rectangle has the lowest A + B:

  • 1 + 24 = 25
  • 2 + 12 = 14
  • 4 + 6 = 10

You can see that 4 x 6 is the most logical rectangle, so we will output 4 x 6 (or 6 x 4).

The rules

  • Given an integer from 1 to 99999, output the most logical rectangle.
  • You may write a function or a program.
  • The spaces in the output are not required.
  • This is , so the submission with the least amount of bytes wins!

Test cases

Input >   Output

1     >   1 x 1
4     >   2 x 2
8     >   4 x 2 (or 2 x 4)
15    >   5 x 3 (or 3 x 5)
47    >   1 x 47 (or 47 x 1)
5040  >   72 x 70 (or 70 x 72)
40320 >   210 x 192 (or 192 x 210)
\$\endgroup\$

marked as duplicate by Reto Koradi, Geobits, Community Dec 13 '15 at 18:12

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1
\$\begingroup\$

CJam, 26 bytes

ri_mQ),W%{1$\%!}=:X/" x "X

or

ri_mQ{)1$\%!},W=):X/" x "X

Test it here.

Finds the largest divisor less than or equal to the square root of the input as one of the two side lengths.

\$\endgroup\$
1
\$\begingroup\$

Pyth, 18 bytes

jd[Kf!%QTs@Q2\x/QK

Try it online: Demonstration or Test Suite

Same idea as Martin's. Finds the first number >= floor(sqrt(n)), that divides n.

Explanation:

jd[Kf!%QTs@Q2\x/QK   implicit: Q = input number
          @Q2        sqrt(Q)
         s           floor, converts ^ to an integer
    f                find the first number T >= floor(sqrt(Q)), that satisfies:
     !%QT               Q mod T == 0
   K                 store this number in K
  [K         \x/QK   create the list [K, "x", Q/K]
jd                   join by spaces
\$\endgroup\$
1
\$\begingroup\$

Java 8, 86 bytes

n->{for(int i=(int)Math.sqrt(n);;i--)if(n%i==0){System.out.print(i+"x"+n/i);return;}};

Lambda function, test with:

public class Rectangle {
    interface Test {
        void run(int v);
    }
    public static void main (String[] args){
        Test test = n->{for(int i=(int)Math.sqrt(n);;i--)if(n%i==0){System.out.print(i+"x"+n/i);return;}};

        int[] testCases = {1, 4, 8, 15, 47, 5040, 40320};
        for (int i : testCases) {
            test.run(i);
            System.out.println();
        }
    }
}

Finds the largest divisor less than or equal to the square root of the input. Same concept as the CJam and Pyth answers.

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.