-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Coprimes.java
42 lines (39 loc) · 1.3 KB
/
Coprimes.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.jwetherell.algorithms.mathematics;
/**
* In number theory, two integers a and b are said to be relatively prime, mutually prime, or coprime (also spelled
* co-prime) if the only positive integer that divides both of them is 1. That is, the only common positive factor
* of the two numbers is 1. This is equivalent to their greatest common divisor being 1.
* <p>
* @see <a href="https://en.wikipedia.org/wiki/Coprime_integers">Mutually Prime / Co-prime (Wikipedia)</a>
* <br>
* @author Szymon Stankiewicz <[email protected]>
* @author Justin Wetherell <[email protected]>
*/
public class Coprimes {
private Coprimes() { }
/**
*
* Euler's totient function. Because this function is multiplicative such implementation is possible.
* <p>
* Time complexity: O(sqrt(n))
* <p>
* @param n Long integer
* @return number of coprimes smaller or equal to n
*/
public static long getNumberOfCoprimes(long n) {
if(n < 1)
return 0;
long res = 1;
for(int i = 2; i*i <= n; i++) {
int times = 0;
while(n%i == 0) {
res *= (times > 0 ? i : i-1);
n /= i;
times++;
}
}
if(n > 1)
res *= n-1;
return res;
}
}