codechef Arranging Cup-cakes题解
2016-04-08 21:54
381 查看
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 ≤ 1001 ≤ N ≤ 108
Example
Input: 4 20 13 8 4 Output: 1 12 2 0
一题简单的因子分解题目。
思路有两个:
1 从根号2開始分解,第一个能够分解的两个因子就是答案
2 利用素数,找出全部的因子,然后求解
这里使用第二中方法。这个比較有挑战性。
#include <stdio.h> #include <stdlib.h> #include <vector> using namespace std; class ArrangingCupcakes { const static int MAX_V = 10001; vector<int> 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<int> 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--) } };
相关文章推荐
- 使用js正则表达式分割内容分别显示
- VC开发数据库基础之ADO篇
- 剑指Offer--003--二维数组中的查找
- FZU 2196 Escape(两次BFS)
- 【计算机视觉】time of flight (TOF)
- 跟着原子学习stm32之内存管理
- BZOJ 3143: [Hnoi2013]游走
- JQ基本知识代码示例
- Android 6.0 运行时权限处理完全解析
- hdoj 2955Robberies<背包>
- 每日之学(2016.04.08)
- Hadoop的分布式架构改进与应用
- Introduction to Partial View
- Andriod——数据存储 SharedPrefrences
- Image Watch插件学习笔记
- 802.11协议精读2:DCF与CSMA/CA
- hdu1284(母函数打表)
- oracle 游标详解
- IntelliJ IDEA的JDK环境配置和Maven依赖管理
- NYOJ 540-奇怪的排序【模拟】