MinPerimeterRectangle

Find the minimal perimeter of any rectangle whose area equals n
ℹ️ © Codility, 2009-2018

Problem

An integer n is given, representing the area of some rectangle.

The area of a rectangle whose sides are of length a and b is a · b, and the perimeter is 2 · (a + b).

The goal is to find the minimal perimeter of any rectangle whose area equals n. The sides of this rectangle should be only integers.

For example, given integer n = 30, rectangles of area 30 are:
• (1, 30), with a perimeter of 62;
• (2, 15), with a perimeter of 34;
• (3, 10), with a perimeter of 26;
• (5, 6), with a perimeter of 22.

Write a function that, given an integer n, returns the minimal perimeter of any rectangle whose area is exactly equal to n.

For example, given an integer n = 30, the function should return 22, as explained above.

Assume that:
n is an integer within the range [1 … 1,000,000,000].

Complexity:
• expected worst-case time complexity is O(sqrt(n));
• expected worst-case space complexity is O(1).

Solution

C#

using System;
class Solution {
  public int solution(int n) {
    int r = 2000000000;
    for (int i = 1; i <= Math.Sqrt(n); i++) {
      if (n % i == 0) {
        int t = 2 * (i + (n / i));
        if (t < r) {
          r = t;
        }
      }
    }
    return r;
  }
}

Java

import java.lang.Math;
class Solution {
  public int solution(int n) {
    int r = 2000000000;
    for (int i = 1; i <= Math.sqrt(n); i++) {
      if (n % i == 0) {
        int t = 2 * (i + (n / i));
        if (t < r) {
          r = t;
        }
      }
    }
    return r;
  }
}

JavaScript

function solution(n) {
  let r = 2000000000;
  for (let i = 1; i <= Math.sqrt(n); i++) {
    if (n % i == 0) {
      let t = 2 * (i + (n / i));
      if (t < r) {
        r = t;
      }
    }
  }
  return r;
}

PHP

function solution($n) {
  $r = 2000000000;
  for ($i = 1; $i <= sqrt($n); $i++) {
    if ($n % $i == 0) {
      $t = 2 * ($i + ($n / $i));
      if ($t < $r) {
        $r = $t;
      }
    }
  }
  return $r;
}