题目来源:码蹄集
https://matiji.net/exam/brushquestion/428/778/B3FCFEC101BD05189BB74D522E019504
参考程序:
#include <iostream>
#include <math.h>
using namespace std;
#define N 100000
int main() {
int n;
cin >> n;
// 未赋值的会被赋值为0
int a[N] = {1, 2};
int tmp = (int)sqrt(n * 1.0);
for (int i = 2; i <= tmp; ++i) {
for (int j = 1; j <= n/2; ++j) {
int index = i * j;
if (index <= n && a[index-1]==0){
a[index-1] = i;
}
}
}
int i = 0;
for (i = 0; i < n-1; ++i) {
if (a[i] == 0){
cout << i+1 << ' ';
} else {
cout << a[i] << ' ';
}
}
if (a[i] == 0){
cout << i+1 << endl;
} else {
cout << a[i] << endl;
}
return 0;
}