【hihocoder 1298】 数论五·欧拉函数

【题目链接】:http://hihocoder.com/problemset/problem/1298

【题意】

【题解】

用欧拉筛法;
能够同时求出1..MAX当中的所有质数和所有数的欧拉函数的值;
基于
以下理论;
如果

n=p^k;这里p是某个质数;
(则只有p的倍数和n是不互质的)

phi[n]=pk1(pk/p1)=(p1)pk1

n为质数;
phi[n] = n-1

若n和p互质;则
phi[np]=phi[n]phi[p]
根据上面那3个结论;
①若i为p的倍数;
则phi[i*p]=phi[i]*p;
因为若i是p的倍数;

i可以表示为p^k*m
这里m是其他质数的乘积
显然p^k和m互质

phi[i] = phi[p^k]*phi[m] = (p-1)*p^(k-1)*phi[m]
phi[i*p]
=phi[p^(k+1)*m]
=phi[p^(k+1)]*phi[m]
=(p-1)*p^k*phi[m]
=(p-1)*p^(k-1)*phi[m]*p
=phi[i]*p
②若i不是p的倍数;
则i和p互质
则phi[i*p]=phi[i]*(p-1);
这里会枚举i和质数p;
容易联想到欧拉筛法;
在做素数筛法的时候顺便把欧拉函数也求出来就好;

【Number Of WA

0

【完整代码】

#include <bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define ms(x,y) memset(x,y,sizeof x)

typedef pair<int,int> pii;
typedef pair<LL,LL> pll;

const int dx[9] = {0,1,-1,0,0,-1,-1,1,1};
const int dy[9] = {0,0,0,-1,1,-1,1,-1,1};
const double pi = acos(-1.0);
const int N = 5e6+100;
const int MAX = 5e6;

bool iszs[N];
vector <int> zsb;
int phi[N],l,r;

int main()
{
    ios::sync_with_stdio(false),cin.tie(0);//scanf,puts,printf not use
    ms(iszs,true);
    rep1(i,2,MAX)
    {
        if (iszs[i])
        {
            zsb.pb(i);
            phi[i] = i-1;
        }
        int len = zsb.size();
        rep1(j,0,len-1)
        {
            int t = zsb[j];
            if (i*t>MAX) break;
            iszs[i*t] = false;
            if (i%t==0)
            {
                phi[i*t] = phi[i]*t;
                break;
            }
            else
                phi[i*t] = phi[i]*(t-1);
        }
    }
    cin >> l >> r;
    int ans = l;
    rep1(i,l+1,r)
        if (phi[ans]>phi[i])
            ans = i;
    cout << ans << endl;
    return 0;
}
posted @ 2017-10-04 18:44  AWCXV  阅读(92)  评论(0编辑  收藏  举报