Two ways to find the Euler function value of a single number:
1#include <iostream>2 using namespacestd;3 4 intPhiintN)5 {6 intAns =N;7 for(inti =2; I * I <= N; i++ )8 {9 if(n% i = =0 )Ten { OneAns-= ans/i; A Do - { -n = n/i; the} while(n% i = =0 ); - } - } - if(n! =1 ) + { -Ans-= ans/N; + } A returnans; at } - - intPphi (intN) - { - intAns =1; - for(inti =2; I * I <= N; i++ ) in { - if(n% i = =0 ) to { +Ans *= I-1; -n = n/i; the while(n% i = =0 ) * { $Ans *=i;Panax Notoginsengn = n/i; - } the } + } A if(n! =1 ) the { +Ans *= N-1; - } $ returnans; $ } - - intMain () the { - intT;WuyiCIN >>T; the while(t-- ) - { Wu intN; -CIN >>N; Aboutcout << pphi (n) <<Endl; $ } - return 0; -}
The Sieve method to find Euler function:
1#include <iostream>2 using namespacestd;3 4 Const intN =32768;5 intPhi[n];6 7 voidInit ()8 {9phi[0] = phi[1] =1;Ten for(inti =2; i < N; i++ ) One { APhi[i] =i; - } - for(inti =2; i < N; i++ ) the { - if(Phi[i] = =i) - { -phi[i]--; + for(intj = i + i; J < N; J + =i) - { +PHI[J]-= phi[j]/i; A } at } - } - } - - intMain () - { in init (); - intT; toCIN >>T; + while(t-- ) - { the intN; *CIN >>N; $cout << Phi[n] <<Endl;Panax Notoginseng } - return 0; the}
Template title: Hdu 1286 POJ 1284
Euler function templates