Codlility---MinPerimeterRectangle
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).
// 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/
随机推荐
- 【非常高%】【codeforces 733B】Parade
time limit per test1 second memory limit per test256 megabytes inputstandard input outputstandard ou ...
- 【record】10.2..10.9
.
- C++闭包,一样很简单
引用百度上对闭包的定义:闭包是指可以包含自由(未绑定到特定对象)变量的代码块:这些变量不是在这个代码块内或者任何全局上下文中定义的,而是在定义代码块的环境中定义(局部变量).“闭包” 一词来源于以下两 ...
- Sql 将多个表查询的结果进行再次查询
把你目前查到结果集定义为一个临时表 tempTable 下面是如何查 SELECT * FROM tempTable where 关键字=‘’举例 select book_num,book_name, ...
- MFC和Qt优缺点 (MFC几乎没有优点、全面下风)
在网上看到的,拿来和大家一起讨论下. 我曾经使用过来开发过软件,我想和大家分享我使用他们时所体会的不同之处. 我并非一个职业作家,这篇文章可能看起来不如专业的杂志和网站上的那么条理清晰.但是,我在这里 ...
- OpenGL(三) RGBA颜色设置
OpenGL支持两种颜色模式:一种是RGBA,一种是颜色索引模式. 像素点附加颜色信息之后,就必须为每一个像素点额外分配一个内存空间保存该点的颜色信息,对于RGBA颜色模式,保存的数据直接代表了颜色, ...
- hdu3118Arbiter (使用二分图的定义,枚举每个状态)
Arbiter Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others) Total Sub ...
- WPF多点触摸放大缩小旋转
原文:WPF多点触摸放大缩小旋转 版权声明:本文为博主原创文章,需要转载尽管转载. https://blog.csdn.net/z5976749/article/details/40118437 如果 ...
- 楼塔当天领袖acm心理(作为励志使用)
楼主个人博客:吉尔博客 假期空闲的时候使用.这些年来GCJ.ACM,TopCoder 的一个号码的一重要的比赛的参与 回顾.GCJ2006 的回顾,今天时间上更早一些吧,我如今还清晰记得3 年 前.我 ...
- [科普]MinGW vs MinGW-W64及其它(比较有意思,来自mingw吧)
部分参照备忘录原文: bitbucket.org/FrankHB/yslib/src/50c3e6344a5a24b2382ce3398065f2197c2bd57e/doc/Workflow.Ann ...