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 的自定义布局做等距布局. 实际做的效果很简单,因为在开发我容易就用到了等距的控件.等距控件就是在指定的宽度下,平均把控件放在水平的地方,这样相等于 ...

  2. Using default security password

    不展示Using default security password的解决办法: import org.springframework.context.annotation.Bean; import ...

  3. Windows下Apache+MySQL+PHP快速配置的几种方法

    Apache MySQL PHP Windows WAMP 1.易思EasySiteServer服务器集成环境 v1.0  (推荐) 尔创互联为推广其ESPCMS而开发的一个小东东,很好用.零配置,完 ...

  4. python 教程 第二十章、 数据库编程

    第二十章. 数据库编程 环境设置 1).安装MySQL-python http://www.lfd.uci.edu/~gohlke/pythonlibs/ MySQL-python-1.2.3.win ...

  5. WPF中用于嵌入其他进程窗口的自定义控件(AppContainer)

    原文:WPF中用于嵌入其他进程窗口的自定义控件(AppContainer) 版权声明:本文为博主原创文章,转载请注明作者和出处 https://blog.csdn.net/ZZZWWWPPP11199 ...

  6. 使用 install.packages() 安装所需的包

    1. 从 CRAN 上安装 install.packages("tm", dependencies = TRUE) tm 程序包用于文本挖掘(text mining) 2. 本地安 ...

  7. 使用Photoshop切图的三种方式

    PhotoShop切图的三种方式 1. 原始切图 (1)选择工具栏中的切片工具 (2)找到要切片的元素,在右侧的图层框中,使元素背景隐藏,然后用切片工具选择需要切片的元素     (3)导出为web常 ...

  8. .net reactor 学习系列(一)---.net reactor介绍

    原文:.net reactor 学习系列(一)---.net reactor介绍       学习.net已经一年多了,从语言的编写到框架类库的运用再到.net三大解决方案的了解(WF,WCF,WPF ...

  9. Android Intent传递对象摘要

    效果: watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvaG9uZ3NoZW5ncGVuZw==/font/5a6L5L2T/fontsize/400/fil ...

  10. Fidder模拟发送请求

    在Fiddler的Composer一栏,可以模拟请求 举例 首先通过浏览器访问页面http://baidu.com/ ,在右侧可以拿到请求情况 在Inspectors一栏可以看到请求和响应结果,复制请 ...