I'm solving the MinPerimeterRectangle problem from Codility:
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:
def solution(N)
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.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [1..1,000,000,000].
I initially used this code:
''' import math
def solution(N):
a = int(math.sqrt(N))
for i in range (a,N+1):
if N % i == 0:
A = int(i)
B = int(N/i)
peri = 2*(A+B)
return(peri)
pass
'''
Received a total score of 60% and the detected time complexity was O(sqrt(N)). Then just by changing the range in line 6, it improved to 100% for the time complexity.
''' import math
def solution(N):
a = int(math.sqrt(N))
for i in range (a,0,-1):
if N % i == 0:
A = int(i)
B = int(N/i)
peri = 2*(A+B)
return(peri)
pass
'''
I noted that for the first one, there were timeout errors when N was a large prime. However, mathematically, I thought the two ranges are of equal length. Why the difference then?