zoukankan      html  css  js  c++  java
  • 欧拉函数及筛法求欧拉函数

    1.欧拉函数

    代码:

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <cstring>
     4 #include <string.h>
     5 #include <math.h>
     6 #include <algorithm>
     7 #include <stack>
     8 #include <queue>
     9 #include <vector>
    10 #include <map>
    11 #include <set>
    12 #define ll long long
    13 const int N=1e6+10;
    14 using namespace std;
    15 typedef pair<int,int>PII;
    16 
    17 int n;
    18 
    19 void get_euler(int x,int res){
    20     for(int i=2;i<=x/i;++i){
    21     if(x%i==0){
    22        res=res/i*(i-1);
    23        while(x%i==0) x/=i;
    24     }
    25     }
    26     if((x>1))  res=res/x*(x-1);
    27     printf("%d\n",res);
    28 }
    29 
    30 int main(){
    31  ios::sync_with_stdio(false);
    32     cin>>n;
    33      while(n--){
    34     int a;
    35      cin>>a;
    36       int t=a;
    37        
    38       get_euler(a,t);
    39      }
    40   return 0;
    41 }

    2.筛法求1~n的欧拉函数之和

    代码:

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <string.h>
    #include <math.h>
    #include <algorithm>
    #include <stack>
    #include <queue>
    #include <vector>
    #include <map>
    #include <set>
    #define ll long long
    const int N=1e6+10;
    using namespace std;
    typedef pair<int,int>PII;
    
    int primes[N],cnt;
    int phi[N];
    bool st[N];
    
    ll get_eulers(int n){
        phi[1]=1;
        for(int i=2;i<=n;++i){
         if(!st[i]){
          primes[cnt++]=i;
          phi[i]=i-1;
        }
        for(int j=0;j<cnt && primes[j]<=n/i;++j){
           st[primes[j]*i]=true;
           if(i%primes[j]==0){
              phi[primes[j]*i]=phi[i]*primes[j];
              break;
           }
         else  phi[primes[j]*i]=phi[i]*(primes[j]-1);
        }
        }
        ll res=0;
        for(int i=1;i<=n;++i) res+=phi[i];
        return res;
    }
    
    int main(){
     ios::sync_with_stdio(false);
     int n;
      cin>>n;
       printf("%lld\n",get_eulers(n));
      return 0;
    }
  • 相关阅读:
    ActiveMQ (二):JMS
    Java消息队列--ActiveMq 初体验
    利用 UltraEdit 重新排版 XML 结构数据
    Java中的Arrays工具类
    数组的下标与长度
    数组的一维与多维
    MySQL数据库的下载与安装
    MySQL数据库的发展历程
    Java中的数组(Array)
    break与continue关键字
  • 原文地址:https://www.cnblogs.com/lr599909928/p/12704284.html
Copyright © 2011-2022 走看看