点击查看代码
//Find all factors of a number
#include<iostream>
#include<cmath>
using namespace std;
void Factors(int n) {
int* factors = new int[n+1]();
for (int i = 1; i <= sqrt(n); i++) {//检测一侧因子即可
if (n % i == 0) {
factors[i-1] = i;//问题:动态数组为n时显示缓冲区溢出
if (i != sqrt(n))
factors[n / i-1] = n / i;//成对放入,减少循环
}
}
for (int i = 0; i <n; i++) {
if (factors[i] != 0)
cout << factors[i] << " ";//输出从小到大
}
cout << endl;
delete []factors;
}//时间复杂度:O(sqrt(n))
int main() {
int n;
cin >> n;
Factors(n);
}