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. 数据集(benchmark)、常用数据集的解析(cifar-10、)

    What is the class of this image ? 主要是以下常见的数据集,用以衡量算法的分类准确率: mnist.cifar-10.cifar-100stl-10 svhn.ILSV ...

  2. Green the world :使用monkey_patch

    eventlet的monkey_patch 用于绿化一些python的模块,看看以下的样例就明确了 urls = ["http://www.haha.mx/joke/1292935" ...

  3. 从文件 I/O 看 Linux 的虚拟文件系统

    1 引言 Linux 中允许众多不同的文件系统共存,如 ext2, ext3, vfat 等.通过使用同一套文件 I/O 系统 调用即可对 Linux 中的任意文件进行操作而无需考虑其所在的具体文件系 ...

  4. JAVA从本机获取IP地址

    JAVA从本机获取IP地址 论述: 此篇博客是在工作的时候,需要获得当前网络下面正确的ip地址,在网上查阅很多博客,网上一个比较普遍的说法是通过InetAddress.getLocalHost().g ...

  5. 于CentOS 6.5编译器安装Git 1.8

    yum install git版本号是太老,它是1.7.1. 在这里,我们将介绍如何编译和安装Git 1.8 yum install curl-devel expat-devel gettext-de ...

  6. 经典书单 —— 语言/算法/机器学习/深度学习/AI/CV/PGM

    0.0 计算机科学 <Lex 与 Yacc> Think Complexity(使用 Python 语言) GitHub - AllenDowney/ThinkComplexity: Co ...

  7. Android能够获取到唯一的设备ID吗?

    Android是否有唯一的设备ID,如果有的话,该怎样快速有效获取? Settings.Secure#ANDROID_ID 返回Android ID ,是一个64位的16进制字符串 1 2 3 imp ...

  8. ios中 微信点击 某个元素 该元素会闪一下

    -webkit-user-select: none;-webkit-tap-highlight-color: rgba(200,200,200,0);

  9. jQuery.noop

    一个空函数 当你仅仅想要传递一个空函数的时候,就用他吧.这对一些插件作者很有用,当插件提供了一个可选的回调函数接口,那么如果调用的时候没有传递这个回调函数,就用jQuery.noop来代替执行.

  10. Erlang实现进程池

    开发工作中,经常会碰到进程池或者线程池,或者其它的资源池.在这里,用erlang实现一个简单的进程池. erlang进程是非常轻量级的,这个进程池的主要目的是用一种通用的方式去管理和限制系统中运行的资 ...