欧拉函数
打巧克力杯周赛的时候,遇到了一道欧拉函数板子题,然而我居然不会(数论全推给队友),结果是我居然用埃氏筛自己打出来了,居然还是对的。
下面是那道题:
例题:
Farey Sequence Length
Given a positive integer, NN, the sequence of all fractions a/ba/b with 0≤a≤b0≤a≤b, 1≤b≤N1≤b≤N and aa and bb relatively prime, listed in increasing order, is called the Farey Sequence of order NN. For example, the Farey Sequence of order 66 is:
0/1,1/6,1/5,1/4,1/3,2/5,1/2,3/5,2/3,3/4,4/5,5/6,1/10/1,1/6,1/5,1/4,1/3,2/5,1/2,3/5,2/3,3/4,4/5,5/6,1/1
For this problem, you will write a program to compute the length of the Farey Sequence of order NN.
Input
The first line of input contains a single integer PP (1≤P≤100001≤P≤10000), which is the number of data sets that follow. Each data set should be processed identically and independently.
Each data set consists of a single line of input. It contains the data set number, KK, followed by the order NN (2≤N≤100002≤N≤10000) of the Farey Sequence whose length is to be found.
Output
For each data set there is a single line of output. The single output line consists of the data set number, KK, followed by a single space followed by the length of the Farey Sequence as a decimal integer.
Sample Input 1 | Sample Output 1 |
---|---|
4 1 6 2 15 3 57 4 9999 |
1 13 2 73 3 1001 4 30393487 |
题意:就是让你求欧拉函数前n项和。
其实正解也是用埃氏筛做的。
比赛代码:
#include <cstdio>
#include <iostream>
using namespace std;
int a[10005];
int ans[10005];
int main()
{
ans[0]=0;
for (int i=1;i<=10000;i++)
{
a[i]=a[i]+i+1;
for (int j=i*2;j<=10000;j+=i)
a[j]-=a[i];
ans[i]=ans[i-1]+a[i];
}
int P,K,N;
cin >> P;
while(P--)
{
scanf("%d%d",&K,&N);
printf("%d %d\n",K,ans[N]);
}
return 0;
}
直接贴模板了,具体公式百度。
欧拉函数模板:
求单个欧拉函数:
int phi(int n)
{
int res=n;
for(int i=2;i*i<=n;i++)
if(n%i==0)
{
res=res-res/i;
while(n%i==0) n/=i;
}
if(n>1)
res=res-res/n;
return res;
}
埃氏筛:
const int SIZE=10000+5;
int phi[SIZE];
void init()
{
memset(phi,0,sizeof(phi));
phi[1]=1;
for (int i=2;i<SIZE;i++)
if(!phi[i])
{
for (int j=i;j<SIZE;j+=i)
{
if(!phi[j]) phi[j]=j;
phi[j]=phi[j]/i*(i-1);
}
}
}
posted on 2018-12-05 23:47 Radium_1209 阅读(108) 评论(0) 编辑 收藏 举报