You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.4 KiB

2 years ago
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 1010;
int primes[N], cnt; // primes[]存储所有素数
bool st[N]; // st[x]存储x是否被筛掉
int d[N]; // d[x]表示x的约数个数
int num[N]; // num[x]表示x的最小质因数的个数
int n;
//欧拉筛法+求约数个数
void get_primes(int n) {
d[1] = 1; // 1的约数只有1个,这个比较特殊
for (int i = 2; i <= n; i++) {
if (!st[i]) {
primes[cnt++] = i;
// i是质数
d[i] = 2; //约数个数是2个一个是1另一个是i
num[i] = 1; //最小质因子个数是1最小质因子就是自己i
}
for (int j = 0; i * primes[j] <= n; j++) {
st[i * primes[j]] = true;
if (i % primes[j] == 0) {
d[i * primes[j]] = d[i] / (num[i] + 1) * (num[i] + 2);
num[i * primes[j]] = num[i] + 1;
break;
} else {
// d[i * primes[j]] = d[i] * d[primes[j]]; 等价于下面的代码 
d[i * primes[j]] = d[i] * 2;
num[i * primes[j]] = 1;
}
}
}
}
int main() {
scanf("%d", &n);
get_primes(n);
//输出1~n之间所有数字的约数个数
for (int i = 1; i <= n; i++) printf("%d %d\n", i, d[i]);
return 0;
}