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/
随机推荐
- 【16.67%】【codeforces 667C】Reberland Linguistics
time limit per test1 second memory limit per test256 megabytes inputstandard input outputstandard ou ...
- Parallel.For
Parallel.For 你可能忽视的一个非常实用的重载方法 说起Parallel.For大家都不会陌生,很简单,不就是一个提供并行功能的for循环吗? 或许大家平时使用到的差不多就是其中最简单 ...
- FontAwesome 图标
FontAwesome 图标 前言 FontAwesome 大家都不陌生,精美的图标,出现在各式各样的网页中.最近在做 Windows Forms 应用程序,要求美观,就想能不能把 FontAweso ...
- WPF的逻辑树与视觉树(3)Visual呈现
原文:WPF的逻辑树与视觉树(3)Visual呈现 这篇就点到为止,挑重点讲 绘图方式有两种 1.继承UIElement,重写OnRender方法 public partial class Windo ...
- 如何更好的利用redis
原文地址http://oldblog.antirez.com/post/take-advantage-of-redis-adding-it-to-your-stack.html @(syoka)[re ...
- Java--数组和链表的区别以及使用场景
数组:是将元素在内存中连续存储的:它的优点:因为数据是连续存储的,内存地址连续,所以在查找数据的时候效率比较高:它的缺点:在存储之前,我们需要申请一块连续的内存空间,并且在编译的时候就必须确定好它的空 ...
- springboot使用logback日志,部署到tomcat不生效问题解决
1.springboot 配置日志方法 使用该方法配置日志,在本地调试可以正常写入日志文件,但是打包发布到tomcat以后日志配置不生效. 2.修改配置 Spring Boot官方推荐优先使用带有-s ...
- debian8 root无法远程登录解决办法
改一下root 密码,应该就能本地登录了. 改/etc/ssh/sshd.conf,然后重启ssh就能远程登录了:PermitRootLogin yesPermitEmptyPasswords no
- Wireshark基本介绍和学习TCP三次握手 专题
wireshark有两种过滤器: 捕捉过滤器(CaptureFilters):用于决定将什么样的信息记录在捕捉结果中.显示过滤器(DisplayFilters):用于在捕捉结果中进行详细查找. 捕捉过 ...
- 运行control userpasswords2实现winXP自动登录
原文:运行control userpasswords2实现winXP自动登录 如果你的计算机只是自己一人在用,且每次都用同一个用户名(或者你根本没在意过什么是用户名),而每次都要输入密码,是否太麻烦了 ...