-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMathUtil.java
More file actions
80 lines (73 loc) · 1.72 KB
/
MathUtil.java
File metadata and controls
80 lines (73 loc) · 1.72 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package name.jacktang.projecteuler.util;
import java.util.TreeMap;
public class MathUtil {
public static boolean isPrime(long num) {
if (num < 2) {
return false;
}
for (int factor = 2; factor < num; factor++) {
if (num % factor == 0) {
return false;
}
}
return true;
}
public static boolean[] generatePrimes(int limit) {
boolean[] numbers = new boolean[limit];
for (int i = 1; i < limit; i++) {
numbers[i] = true;
}
int i = 1;
while (i + 1 <= Math.sqrt(limit)) {
for (int multiple = 2; (i + 1) * multiple <= limit; multiple++) {
numbers[(i + 1) * multiple - 1] = false;
}
i++;
while (!numbers[i]) {
i++;
}
}
return numbers;
}
public static boolean isPalindrome(int num) {
String numString = String.valueOf(num);
for (int i = 0; i < numString.length() / 2 + 1; i++) {
if (numString.charAt(i) != numString.charAt(numString.length() - i - 1)) {
return false;
}
}
return true;
}
public static TreeMap<Long, Integer> getPrimeFactors(long num) {
TreeMap<Long, Integer> factors = new TreeMap<>();
while (num % 2 == 0) {
factors.put(2L, factors.containsKey(2L) ? factors.get(2L) + 1 : 1);
num /= 2;
}
for (int i = 3; i <= Math.sqrt(num); i += 2) {
while (num % i == 0) {
factors.put((long) i, factors.containsKey((long) i) ? factors.get((long) i) + 1 : 1);
num /= i;
}
}
if (num > 2) {
factors.put(num, 1);
}
return factors;
}
public static long isPowerNumber(long num, long maxBase) {
for (long base = 2; base <= maxBase; base++) {
long devision = num;
while (devision != 1) {
if (devision % base != 0) {
break;
}
devision /= base;
}
if (devision == 1) {
return base;
}
}
return 0;
}
}