紫书题解汇总:[紫书CH0] 《算法竞赛入门经典》(第2版) 题解目录
1. 题目来源
2. 题目说明

中文描述:

3. 题目解析
方法一:唯一分解定理+大素数
题意也是很明确了,很容易能想到这是唯一分解定理,因为这样分解都是素数的幂积,不会产生两两直接存在约数的情况,也就符合题目要求。
题目坑点蛮多的,至少两个整数意味着若该数为素数、为 1、为整数次方时即唯一分解仅有 1 个因子的情况下,就需要加上一个挂件数 1,最后结果也得加 1。
还有个坑点 n=2^31 −1 时,输出的数为 2147483648 这是个素数,加 1 后超出了 int 的存储范围,最好用 long long 存储。这个属实没发现…被恶心到了嗷。
来自百度百科,再膜一下祖师爷:

参见代码如下:
#include <iostream>
#include <algorithm>
#include <math.h>
using namespace std;
// 质因子分解
int divide_all(int& n, int d) {
int x = 1;
while (n % d == 0) {
n /= d;
x *= d;
}
return x;
}
long long solve(int n) {
if (n == 1) return 2;
// floor向下取整,+0.5即四舍五入扩大精度
int m = floor(sqrt(n) + 0.5);
long long ans = 0, cnt = 0; // cnt素数个数,ans答案最小和
for (int i = 2; i < m; ++i) {
if (n % i == 0) { // 新的素因子
++cnt;
cout << i << endl;
ans += divide_all(n, i);
}
}
if (n > 1) ++cnt, ans += n;
if (cnt <= 1) ++ans;
return ans;
}
int main() {
int n, tmp = 0;
while (cin >> n and n)
cout << "Case " << ++tmp << ": " << solve(n) << "\n";
return 0;
}
本文针对《算法竞赛入门经典》第二版中UVA10791题目进行解析,采用唯一分解定理结合大素数策略,解决最小和倍数问题。讨论了素数、整数次方等特殊情况,并分享了使用C++实现的代码。
1223





