欧拉函数(代码)

昨天在TYVJ上做模拟赛,第二题涉及到了欧拉函数的知识,因此自己恶补了一下数学知识。

欧拉函数:给定一个数N,求出小于N的和互质的书的个数;

公式  Φ(N)=N*(1-1/P1)*(1-1/P2)*(1-1/P3)....*(1-1/Pn);

      其中,P1...Pn(n的质因子)

由上面的公式,可以想出下面的那段C++代码的思路:

#include <fstream>
#include <cstring>
#include <cmath>
using namespace std;
int main()
{
    int n,q;
    cin>>n;
    q=(int)(sqrt(n));
    int res=n;
    for (int i=2;i<=q;i++)
    {
        if (n%i==0)
        {
                   res=(res/i)*(i-1);
                   while (n%i==0)
                     n=n/i; 
        }
    }
    if (n!=0)
      res=(res/n)*(n-1);
    cout<<res<<endl;
    return 0;
}  

 

posted @ 2010-11-06 16:14  forever zsz  阅读(549)  评论(0编辑  收藏  举报