欧拉函数

来源:互联网 发布:网络教育不考学位证 编辑:程序博客网 时间:2024/06/07 00:28

欧拉函数定义:

函数 phi(x)  为 小于等于x且与 x互质的整数的个数。 phi(x)=x(1-1/p1)(1-1/p2)......(1-1/pn);


如果知道欧几里德算法的话就应该知道gcd(b×t+a,b)=gcd(a,b)  (t为任意整数)


则如果a与b互素,则b×t+a与b也一定互素;如果a与b不互素,则b×t+a与b也一定不互素


故与m互素的数对m取模具有周期性


欧拉函数计算:

int euler_phi(int n)
{
    int m=(int)sqrt(n+0.5);//防止越界
    int ans=n;
    for(int i=2;i<=m;i++)
        if(n%i==0)//找素因子
        {
            ans=ans/i*(i-1);
            while(n%i==0)n/=i;//除尽
        }
    if(n>1)ans=ans/n*(n-1);
}

欧拉函数打表:

int 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);
            }
}


例题:poj 2773 Happy 2006 


Two positive integers are said to be relatively prime to each other if the Great Common Divisor (GCD) is 1. For instance, 1, 3, 5, 7, 9...are all relatively prime to 2006.

Now your job is easy: for the given integer m, find the K-th element which is relatively prime to m when these elements are sorted in ascending order.



Input


The input contains multiple test cases. For each test case, it contains two integers m (1 <= m <= 1000000), K (1 <= K <= 100000000).


Output


Output the K-th element in a single line.


Sample Input

2006 1
2006 2
2006 3



Sample Output

1
3
5

<span style="font-family:Arial;">#include <iostream>#include<cmath>#include<stdio.h>using namespace std;int phi[100005],mark[100005];int getphi(int n){    int m=(int)sqrt(n+0.5);//防止越界    int ans=n;    for(int i=2;i<=m;i++)        if(n%i==0)//找素因子        {            ans=ans/i*(i-1);            while(n%i==0)n/=i;//除尽        }    if(n>1)ans=ans/n*(n-1);    return ans;}int gcd(int a,int b){    if(b==0) return a;    return gcd(b,a%b);}int main(){    int n,m;    while(scanf("%d %d",&n,&m)!=EOF)    {        int ans=getphi(n);        int k=(m-1)/ans,j=m%ans,t=0;        //cout<<k<<" "<<j<<endl;        if(!j) j=ans;        long long int y;        for(int i=1;i<=n;i++)        {            if(gcd(i,n)==1)            {                t++;            }            if(t==j)            {                y=k*n+i;                 break;            }        }        cout<<y<<endl;    }    return 0;}</span><span style="font-family:微软雅黑;"></span>


1 0