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