Task description

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 theperimeter 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:

class Solution { public int solution(int 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.

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

 
Programming language used: Java
Code: 00:48:19 UTC, java, final, score:  100
// you can also use imports, for example:
// import java.util.*; // you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message"); class Solution {
public int solution(int N) {
// write your code in Java SE 8
int max_perimeter = 2*(1+N);
for(int i=2; i < Math.sqrt(N)+1; i++) {
if(N%i == 0) {
max_perimeter = Math.min(max_perimeter, 2*(i+N/i));
}
}
return max_perimeter;
}
}
https://codility.com/demo/results/training8VZXU6-PUT/

随机推荐

  1. WPF 触摸到事件

    原文:WPF 触摸到事件 本文从代码底层告诉大家,在触摸屏幕之后是如何拿到触摸点并且转换为事件 在 WPF 界面框架核心就是交互和渲染,触摸是交互的一部分.在 WPF 是需要使用多个线程来做触摸和渲染 ...

  2. 读取和修改xml文件

    如有一个xml文件DownData.xml,内容如下 <?xml version="1.0" standalone="yes"?> <Root ...

  3. Docker简单的使用命令

    Hello World 使用[docker run]命令在docker container中执行应用程序 <pre name="code" class="plain ...

  4. e.target e.currenttarget

    概述 当事件穿过 DOM 时,识别事件的当前目标对象(Identifies the current target for the event, as the event traverses the D ...

  5. WPF 同一窗口内的多线程/多进程 UI(使用 SetParent 嵌入另一个窗口)

    原文 WPF 同一窗口内的多线程/多进程 UI(使用 SetParent 嵌入另一个窗口) WPF 的 UI 逻辑只在同一个线程中,这是学习 WPF 开发中大家几乎都会学习到的经验.如果希望做不同线程 ...

  6. 在.net core中一个简单的加密算法

    using System; using System.Text; //System.Security下加密算法的命名空间 using System.Security.Cryptography; nam ...

  7. Matlab Tricks(十八)—— 矩阵间元素距离的计算

    两个矩阵间元素(向量)距离的度量,首先想到的是遍历,循环的方式,显然 matlab 下的编程并不推荐,matlab 下矩阵向量化编程效率尤高. 先考虑两个向量距离的计算: ∥x−y∥2=∥x∥2+∥y ...

  8. 解析Android的 消息传递机制Handler

    1. 什么是Handler: Handler 网络释义"机械手.经理"意思,在Android它用于管理多个线程UI操作: 2. 为什么会出现Handler: 在Android里面的 ...

  9. CSRF 专题

    一.CSRF是什么? CSRF(Cross-site request forgery),中文名称:跨站请求伪造.      也被称为:one click attack/session riding(一 ...

  10. Android Fragment——详细解释

    1.Fragment概述 在一个Activity中. Fragment代表UI的一个部分或者一个行为.一个Activity能够结合多个Fragment对象,也能够在多个activity中使用同样Fra ...