D - Farey Sequence
题目明说了:a/b with 0 < a < b <= n and gcd(a,b) = 1。所以,对每个数x,我们只要找出比x小与x互素的数的总数phi(x)出来就可以,然后对每一个n答案就是sum{phi(i)},i∈[2,n]。找比x小与x互素的数的总数可以用到欧拉函数,我也不知道原理是什么我直接抄模板的……
#include <cstdio> #include <algorithm> #include <cstring> #include <iostream> using namespace std; typedef long long LL; const int MAXN = 1000010; LL phi[MAXN]; void phi_table(int n) { //for(int i = 2; i <= n; ++i) phi[i] = 0; phi[1] = 1; for(int i = 2; i <= n; ++i) if(!phi[i]) for(int j = i; j <= n; j += i) { if(!phi[j]) phi[j] = j; phi[j] = phi[j] / i * (i - 1); } } int main() { phi_table(1000000); for(int i = 3; i <= 1000000; ++i) phi[i] += phi[i - 1]; int n; while(scanf("%d", &n) != EOF) { if(n == 0) break; cout<<phi[n]<<endl; } }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步