JavaAlgorithms/Others/EulersFunction.java

28 lines
744 B
Java
Raw Normal View History

package Others;
/**
* You can read more about Euler's totient function
* <p>
* See https://en.wikipedia.org/wiki/Euler%27s_totient_function
*/
2019-02-03 22:48:44 +08:00
public class EulersFunction {
2019-02-04 11:27:42 +08:00
// This method returns us number of x that (x < n) and gcd(x, n) == 1 in O(sqrt(n)) time complexity;
2019-02-03 22:48:44 +08:00
public static int getEuler(int n) {
int result = n;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
2019-02-03 22:48:44 +08:00
while (n % i == 0) n /= i;
result -= result / i;
}
}
if (n > 1) result -= result / n;
return result;
}
2019-02-03 22:48:44 +08:00
public static void main(String[] args) {
2019-02-04 11:27:42 +08:00
for (int i = 1; i < 100; i++) {
2019-02-03 22:48:44 +08:00
System.out.println(getEuler(i));
}
}
}