任何一个合数可以分解为几个质数的乘积,这些质数也必然是这个合数的约数。

超时模板:

#include<bits/stdc++.h>
using namespace std;
vector<int> fun(int n) {
	vector<int> v;
	for (int i = 2; i <= n; i++) {
		while (n%i == 0) {
			n /= i;
			v.push_back(i);
		}
	}
	return v;
}
int main() {
	int n;
	cin >> n;
	vector<int> v = fun(n);
	for (auto it = v.begin(); it != v.end(); it++) {
		cout << *it << " ";
	}
}

优化模板:

#include<iostream>
#include<vector>
#include<cmath>
using namespace std;
vector<int> fac;
void Divide(int m) {
	if (m % 2 == 0) {
		fac.push_back(2);
		while (m % 2 == 0)m /= 2;	//去重 
	}
	for (int i = 3; i <= sqrt(m); i += 2) {
		if (m%i == 0) {
			fac.push_back(i);
			while (m%i == 0)m /= i;
		}
	}
	if (m > 2)fac.push_back(m);	//判断还有没有最后一个
}
int main() {
	int m;
	while (cin >> m) {
		fac.clear();
		Divide(m);
		for (vector<int>::iterator it = fac.begin(); it != fac.end(); it++) {
			cout << *it << " ";
		}
		putchar(10);
	}
}