欧拉函数的算法实现

    xiaoxiao2021-03-25  75

    欧拉函数:在数论,对正整数n,欧拉函数是小于等于n的数中与n互质的数的数目。 公式:∅(x)=(x)(1-1/p1)(1-1/p2)······(1-1/pn),其中p1···pn是x的素因数。

    long long phi(long long int n) { long long res=n; for(long long i=2;i*i<=n;i++) {//任何一个和数均可以差写成两个或者多个素数的乘积且任何一个合数都至少有一个不超过根号n的素因子; if(n%i==0)//首先判断i是n的因子(其实这里的判断就是在判断n的素因子); { res=res-res/i;//公式 while(n%i==0) { n=n/i;//除掉的n中所有包含当前i为因子的数,所以在if处就是将i的素因子筛选出来了; } } } if(n>1)//处理最后一个数 { res=res-res/n;//还是公式; } return res; }//再此代码的基础上还可以用素数打表将其优化,请大家积极尝试 //打表 void phi_1() { for(int i=1;i<=maxn;i++) { p[i]=i;///预置公式中的n; } for(int i=2;i<=maxn;i++) { if(p[i]==i) { for(int j=i;j<=maxn;j+=i)//j+=i处理了因子为i的数字,更改之后p[i]==i不成立,以此筛选素因子,相当于找到素因子,然后让素因子自己去寻找他的倍数,然后使用公式。 { p[j]=p[j]-p[j]/i;//同样是用公式 } } } }

    POJ2407

    Description

    Given n, a positive integer, how many positive integers less than n are relatively prime to n? Two integers a and b are relatively prime if there are no integers x > 1, y > 0, z > 0 such that a = xy and b = xz.

    Input

    There are several test cases. For each test case, standard input contains a line with n <= 1,000,000,000. A line containing 0 follows the last case.

    Output

    For each test case there should be single line of output answering the question posed above.

    Sample Input

    7 12 0

    Sample Output

    6 4 代码如下:

    #include <iostream> using namespace std; long long int phi(long long int n); int main() { long long int n; while(cin>>n) { if(n==0) break; long long int ans=phi(n); cout<<ans<<endl; } return 0; } long long int phi(long long int n) { long long res=n; for(long long int i=2;i*i<=n;i++) { if(n%i==0) { res=res-res/i; while(n%i==0) n=n/i; } } if(n>1) res=res-res/n; return res; }
    转载请注明原文地址: https://ju.6miu.com/read-36369.html

    最新回复(0)