1
19
20 package com.liferay.portal.kernel.util;
21
22 import com.liferay.portal.kernel.log.Log;
23 import com.liferay.portal.kernel.log.LogFactoryUtil;
24
25 import java.text.NumberFormat;
26
27 import java.util.HashMap;
28 import java.util.Map;
29
30
36 public class MathUtil {
37
38 public static int base2Log(long x) {
39 return _base2LogValues.get(x);
40 }
41
42 public static long base2Pow(int x) {
43 if (x == 0) {
44 return 1;
45 }
46 else {
47 return 2L << (x - 1);
48 }
49 }
50
51 public static int factorial(int x) {
52 if (x < 0) {
53 return 0;
54 }
55
56 int factorial = 1;
57
58 while (x > 1) {
59 factorial = factorial * x;
60 x = x - 1;
61 }
62
63 return factorial;
64 }
65
66 public static double format(double x, int max, int min) {
67 NumberFormat nf = NumberFormat.getInstance();
68
69 nf.setMaximumFractionDigits(max);
70 nf.setMinimumFractionDigits(min);
71
72 try {
73 Number number = nf.parse(nf.format(x));
74
75 x = number.doubleValue();
76 }
77 catch (Exception e) {
78 _log.error(e.getMessage());
79 }
80
81 return x;
82 }
83
84 public static boolean isEven(int x) {
85 if ((x % 2) == 0) {
86 return true;
87 }
88
89 return false;
90 }
91
92 public static boolean isOdd(int x) {
93 return !isEven(x);
94 }
95
96 public static int[] generatePrimes(int max) {
97 if (max < 2) {
98 return new int[0];
99 }
100 else {
101 boolean[] crossedOut = new boolean[max + 1];
102
103 for (int i = 2; i < crossedOut.length; i++) {
104 crossedOut[i] = false;
105 }
106
107 int limit = (int)Math.sqrt(crossedOut.length);
108
109 for (int i = 2; i <= limit; i++) {
110 if (!crossedOut[i]) {
111 for (int multiple = 2 * i; multiple < crossedOut.length;
112 multiple += i) {
113
114 crossedOut[multiple] = true;
115 }
116 }
117 }
118
119 int uncrossedCount = 0;
120
121 for (int i = 2; i < crossedOut.length; i++) {
122 if (!crossedOut[i]) {
123 uncrossedCount++;
124 }
125 }
126
127 int[] result = new int[uncrossedCount];
128
129 for (int i = 2, j = 0; i < crossedOut.length; i++) {
130 if (!crossedOut[i]) {
131 result[j++] = i;
132 }
133 }
134
135 return result;
136 }
137 }
138
139 private static Log _log = LogFactoryUtil.getLog(MathUtil.class);
140
141 private static Map<Long, Integer> _base2LogValues =
142 new HashMap<Long, Integer>();
143
144 static {
145 _base2LogValues.put(0L, Integer.MIN_VALUE);
146
147 for (int i = 0; i < 63; i++) {
148 _base2LogValues.put(base2Pow(i), i);
149 }
150 }
151
152 }