1 条题解
-
0
练46.2 求丑数
解题思路
判断函数依次反复除尽因子2、3、5,剩余为1即丑数。枚举1~100,符合的按每行10个、每个宽6输出,最后输出计数。
正确性说明
计算规则直接来自题目定义。按所述顺序处理时,已完成部分的结果被准确保存在累加量、计数或当前状态中;下一步只加入新增贡献。最终得到完整要求的结果。
易错点
1也是丑数;最后不足10个也要换行,再写个数。
复杂度
固定枚举范围,时间O(1),空间O(1)。
参考代码(C++11)
#include <bits/stdc++.h> using namespace std; bool ugly(int x) { for (int p : {2, 3, 5}) while (x % p == 0) x /= p; return x == 1; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int count = 0; for (int x = 1; x <= 100; x++) if (ugly(x)) { cout << setw(6) << x; count++; if (count % 10 == 0) cout << "\n"; } if (count % 10) cout << "\n"; cout << "个数:" << count << "\n"; return 0; }
- 1