代码
#include <iostream>
using namespace std;
typedef long long LL;
const int N = 1000010;
int primes[N], cnt;
int euler[N];
bool st[N];
/*
线性筛法求[1,n]所有数的欧拉函数和 @ 利用引理来简化phi(i)的求导
*/
void get_eulers(int n)
{
euler[1] = 1;
for (int i = 2; i <= n; i ++ )
{
if (!st[i])
{
primes[cnt ++ ] = i;
// lemma 1
euler[i] = i - 1;
}
for (int j = 0; primes[j] <= n / i; j ++ )
{
int t = primes[j] * i;
st[t] = true;
// lemma 4
if (i % primes[j] == 0)
{
euler[t] = euler[i] * primes[j];
break;
}
// lemma 3
euler[t] = euler[i] * (primes[j] - 1);
}
}
}
int main()
{
int n;
cin >> n;
get_eulers(n);
LL res = 0;
for (int i = 1; i <= n; i ++ ) res += euler[i];
cout << res << endl;
return 0;
}
为什么 i % primes[j] != 0 则它们互质?
ok
orz
赞!