Euler function (template)

Coprime is the number 1 of the Convention only two integers, called relatively prime integers

 

1. By definition solving

 1 to 6 with example 6 1,5 prime number only, it is the Euler function 6 2

 

 Seeking a time complexity: O (sqrt (n)) is the number of n - n * sqrt (n)

               long res=n;
                        for(int i=2;i<=n/i;i++){
                                if(n%i==0){
                                        res=res*(i-1)/i;
                                        while(n%i==0) n/=i;
                                }
                        }
                        if(n>1) res=res*(n-1)/n;
                        System.out.println(res);

 

2. Sieve Method Euler function, time complexity: O (n)

       i% primes [j] == 0 when: primes [J] is the smallest prime factors of i, but also primes [j] * i minimum quality factor, i.e. i and i * prime [j] have the same quality factor

         

      ! i% primes [J] = 0 : primes [J] i is not a prime factor, but primes [j] * i minimum quality factor, so much the prime factors of a

      

 

 

static final int N=1000005;
        static int prime[]=new int[N];
        static boolean vis[]=new boolean[N];
        static int phi[]=new int[N];
        static int cnt,n;
        static void get_eulers(){
                Phi [ . 1] =. 1 ;.. 1. 1 // Euler function. 1
                 for ( int I = 2; I <N; I ++ ) {
                         IF (! {VIS [I])
                                prime[cnt++]=i;
                                Phi [I] = i-1 ;. 2 // Euler function is a prime number i-1
                        }
                        for(int j=0;j<cnt&&prime[j]<N/i;j++){
                                vis[prime[j]*i]=true;
                                if(i%prime[j]==0) {
                                        Phi [prime [j] * i] = Phi [i] * prime [j];.. 3 // If prime [j] is the smallest prime factors of i
                                         BREAK ;
                                }
                                else{
                                        Phi [Prime [J] * I] Phi = [I] * (Prime [J] -1 );.. 4 // not minimum quality factor
                                }
                        }
                }
                int res=0;
                for(int i=1;i<=n;i++) res+=phi[i];
                System.out.println(res);
                
        }

 

Guess you like

Origin www.cnblogs.com/qdu-lkc/p/12260122.html