-
Notifications
You must be signed in to change notification settings - Fork 21.3k
Expand file tree
/
Copy pathMobiusFunction.java
More file actions
58 lines (52 loc) · 2.21 KB
/
Copy pathMobiusFunction.java
File metadata and controls
58 lines (52 loc) · 2.21 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.thealgorithms.maths.Prime;
/*
* Java program for mobius function
* For any positive integer n, define μ(n) as the sum of the primitive nth roots of unity.
* It has values in {−1, 0, 1} depending on the factorization of n into prime factors:
* μ(n) = +1 if n is a square-free positive integer with an even number of prime factors.
* μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors.
* μ(n) = 0 if n has a squared prime factor.
* Wikipedia: https://en.wikipedia.org/wiki/M%C3%B6bius_function
*
* Author: Akshay Dubey (https://github.com/itsAkshayDubey)
*
* */
public final class MobiusFunction {
private MobiusFunction() {
}
/**
* This method returns μ(n) of given number n
*
* @param number Integer value which μ(n) is to be calculated
* @return 1 when number is less than or equals 1
* or number has even number of prime factors
* 0 when number has repeated prime factor
* -1 when number has odd number of prime factors
*/
public static int mobius(int number) {
if (number <= 0) {
// throw exception when number is less than or is zero
throw new IllegalArgumentException("Number must be greater than zero.");
}
int primeFactorCount = 0;
int remaining = number;
/* Divide out every prime factor in turn. Trial division only has to run up to the square
root of the remaining value, and the multiplication is widened to long so that the bound
does not overflow for numbers close to Integer.MAX_VALUE. */
for (int factor = 2; (long) factor * factor <= remaining; factor++) {
if (remaining % factor == 0) {
remaining /= factor;
if (remaining % factor == 0) {
// number is divisible by the square of this prime factor
return 0;
}
primeFactorCount++;
}
}
/* Whatever is left is either 1 or a single prime factor larger than the square root. */
if (remaining > 1) {
primeFactorCount++;
}
return (primeFactorCount % 2 == 0) ? 1 : -1;
}
}