1 条题解
-
0
【例46.1】 完全数
解题思路
对每个x=2~n枚举其小于自身的正因子,求和并暂存。若因子和等于x,按指定前缀输出x及因子列表。
正确性说明
计算规则直接来自题目定义。按所述顺序处理时,已完成部分的结果被准确保存在累加量、计数或当前状态中;下一步只加入新增贡献。最终得到完整要求的结果。
易错点
自身不算因子;1不是完全数。
复杂度
时间O(n²),空间O(n)。
参考代码(C++11)
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; for (int x = 2; x <= n; x++) { vector<int> v; int sum = 0; for (int d = 1; d < x; d++) if (x % d == 0) { sum += d; v.push_back(d); } if (sum == x) { cout << x << " its factors are"; for (int d : v) cout << " " << d; cout << "\n"; } } return 0; }
- 1