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