博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
codechef Arranging Cup-cakes题解
阅读量:7104 次
发布时间:2019-06-28

本文共 2505 字,大约阅读时间需要 8 分钟。

Arranging Cup-cakes

Our Chef is catering for a big corporate office party and is busy preparing different mouth watering dishes. The host has insisted that he serves his delicious cupcakes for dessert.

On the day of the party, the Chef was over-seeing all the food arrangements as well, ensuring that every item was in its designated position. The host was satisfied with everything except the cupcakes. He noticed they were arranged neatly in the shape of a rectangle. He asks the Chef to make it as square-like as possible.

The Chef is in no mood to waste his cupcakes by transforming it into a perfect square arrangement. Instead, to fool the host, he asks you to arrange the N cupcakes as a rectangle so that the differencebetween the length and the width is minimized.

Input

The first line of the input file contains an integer T, the number of test cases. Each of the following T lines contains a single integer N denoting the number of cupcakes.

Output

Output T lines, each indicating the minimum possible difference between the length and the width in a rectangular arrangement of the cupcakes.

Constraints

1 ≤ T ≤ 100

1 ≤ N ≤ 108

Example

Input:4201384Output:11220

一题简单的因子分解题目。

思路有两个:

1 从根号2開始分解,第一个能够分解的两个因子就是答案

2 利用素数,找出全部的因子,然后求解

这里使用第二中方法。这个比較有挑战性。

#include 
#include
#include
using namespace std;class ArrangingCupcakes{ const static int MAX_V = 10001; vector
sieve; void genSieve() { bool A[MAX_V] = {false}; for (int i = 2; i < MAX_V; i++) { if (!A[i]) { for (int j = (i<<1); j < MAX_V; j+=i) { A[j] = true; } sieve.push_back(i); } } }public: ArrangingCupcakes() : sieve() { genSieve(); int T = 0, N = 0; scanf("%d", &T); while (T--) { scanf("%d", &N);//写成sanf("%d", N)就会程序崩溃 vector
divs(1, 1); int n = N; for (int i = 0; i < (int)sieve.size() && n > 1; i++) { int sq = sieve[i]; if (sq * sq > n) sq = n; if (n % sq == 0) { int degree = 0; for ( ; n % sq == 0; degree++) n /= sq; for (int j = int(divs.size()) - 1; j >= 0 ; j--) { int d = divs[j]; for (int k = 0; k < degree; k++) { d *= sq; divs.push_back(d); } } }//if (n % sq == 0) }//求因子分解 int ans = N - 1; for (int i = 0; i < (int)divs.size(); i++) { ans = min(ans, abs(N/divs[i] - divs[i])); } printf("%d\n", ans); }//while (T--) }};


本文转自mfrbuaa博客园博客,原文链接:http://www.cnblogs.com/mfrbuaa/p/5370121.html,如需转载请自行联系原作者   

你可能感兴趣的文章
组策略部署软件之四:部署Service pack和补丁
查看>>
【开篇导航】—Entity Framework实例详解
查看>>
mprotect: 设置内存访问权限
查看>>
signal函数、sigaction函数及信号集操作函数
查看>>
linux常用命令2
查看>>
SQL Server 环形缓冲区(Ring Buffer) -- SQL Server的Ring Buffer类型
查看>>
OutCallReceiver
查看>>
网络的理解2
查看>>
python中的map、filter、reduce函数
查看>>
Exchange 2016 之分层通讯簿
查看>>
【Java例题】4.3 3. 使用Gauss消元法求解n元一次方程组的根,
查看>>
SSH 认证
查看>>
MySQL学习总结(二)
查看>>
Android 开发环境搭建(MyEclipse+Android sdk+ADT环境)
查看>>
金蝶系统(V12),防火墙需要开启的端口
查看>>
一:响应头信息
查看>>
我的友情链接
查看>>
使用angularjs对数据进行排序筛选
查看>>
创建可弹性调整文件系统的 LVM 卷组
查看>>
mailx配置特定邮箱发信
查看>>