• 欧拉函数


     Relatives

     use MathJax to parse formulas

    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

     首先讲一下欧拉函数    例如φ(8)=4,因为1,3,5,7均和8互质

    计算方法  当n是素数时  答案为n-1  

     当n不是是素数时   

    通式:φ(x)=x(1-1/p1)(1-1/p2)(1-1/p3)(1-1/p4)…..(1-1/pn)
    其中p1, p2……pnx的所有质因数,x是不为0的整数

    #include <iostream>
    #include <algorithm>
    #include <cstdio>
    #include <cmath>
    #include <cstring>
    #include <cstdlib>
    using namespace std;
    typedef long long ll ;
    ll OL(ll n){ //返回euler(n)   
        int res=n,a=n;  
        for(ll i=2;i*i<=a;i++){//从小到大尝试n的质因数 
            if(a%i==0){//如果i是n的质因数 
                res=res/i*(i-1);//提了一个1/i出来,先进行除法是为了防止中间数据的溢出   
                while(a%i==0) a/=i;//欧拉函数只记算一种质因数 
            }  
        }  
        if(a>1) res=res/a*(a-1);//如果最后还剩因子 
        return res;  
    }
    int main()
    {
        ll n;
        while(1)
        {
            cin>>n;
            if(n==0)
                break;
            ll ans=OL(n);
            cout<<ans<<endl;
        }
        return 0;
    }
  • 相关阅读:
    多元高斯分布(斯坦福machine learning week 9)
    异常检测(斯坦福machine learning week 9)
    Python编码透析
    nlp Python库之pynlpir
    降维(斯坦福machine learning week 8)
    主成分分析PCA之协方差矩阵的理解
    聚类(斯坦福machine learning week 8)
    svm之使用SVM(斯坦福machine learning week 7)
    java泛型总结
    Java之IO流学习总结
  • 原文地址:https://www.cnblogs.com/zcy19990813/p/9702700.html
Copyright © 2020-2023  润新知