双重循环遍历2-sqrt(n)。遍历完,如果找不到因子,则此数为质数。
#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <vector>
using namespace std;
int main(void)
{
int n, upper, i, j, tmpn;
vector<int> consecfactor, tmp;
scanf("%d", &n);
upper = (int)sqrt(n) + 1;
tmpn = n;
for (i = 2; i < upper; i++) {
for (j = i; j < upper; j++) {
if (tmpn % j) {
if (tmp.size() > consecfactor.size()) {
consecfactor = tmp;
}
tmp.clear();
tmpn = n;
break;
}
else {
tmp.push_back(j);
tmpn /= j;
}
}
}
if (tmp.size() == 0 && consecfactor.size() == 0) {
consecfactor.push_back(n);
}
else if (tmp.size() > consecfactor.size()) {
consecfactor = tmp;
}
printf("%d\n%d", consecfactor.size(), consecfactor[0]);
for (int i = 1; i < consecfactor.size(); i++) {
printf("*%d", consecfactor[i]);
}
return 0;
}