Codility 'MinPerimeterRectangle' Solution

Martin Kysel · July 29, 2014

Short Problem Definition:

Find the minimal perimeter of any rectangle whose area equals N.

MinPerimeterRectangle

Complexity:

expected worst-case time complexity is O(sqrt(N))

expected worst-case space complexity is O(1).

Execution:

Trivial search for the largest prime.

Solution:

import math
def solution(N):
    if N <= 0:
      return 0
  
    for i in xrange(int(math.sqrt(N)), 0, -1):
        if N % i == 0:
            return 2*(i+N/i)
            
    raise Exception("should never reach here!")    

Twitter, Facebook

To learn more about solving Coding Challenges in Python, I recommend these courses: Educative.io Python Algorithms, Educative.io Python Coding Interview.