51nod_1136 欧拉函数

来源:互联网 发布:类似爱情2只有我知结局 编辑:程序博客网 时间:2024/06/01 09:04

1136 欧拉函数
基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题 收藏 取消关注
对正整数n,欧拉函数是少于或等于n的数中与n互质的数的数目。此函数以其首名研究者欧拉命名,它又称为Euler’s totient function、φ函数、欧拉商数等。例如:φ(8) = 4(Phi(8) = 4),因为1,3,5,7均和8互质。
Input
输入一个数N。(2 <= N <= 10^9)
Output
输出Phi(n)。
Input示例
8
Output示例
4

思路:裸的欧拉函数
φ(x)=x(1-1/p1)(1-1/p2)……….(1-1/pn)
p1,p2,,,,pn为x的唯一素因子
如:8=2*2*2 ,φ(8)=8*(1-1/2)=4;

代码:

#include<cstdio>#include<iostream>#include<cmath>using namespace std;int euler(int n){    //euler(x)=x(1-1/p1)(1-1/p2)(1-1/p3)....(1-1/pn)//唯一素因子     double res=1;    res=n;     bool f=1;    for(int i=2;i<=sqrt(n);i++){        if(n==1)        break;        if(n%i==0){            f=0;        //  cout<<(1.0/i)<<endl;            res=(res-res/i);            while(n%i==0){                n/=i;            }        }     }    if(f)    return n-1;    if(n>1)    res=(res-res/n);    return res;}int main(){    int n;    cin>>n;    cout<<euler(n)<<endl;    return 0;}
0 0