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
33 public class MathUtil {
34
35 public static int factorial(int x) {
36 if (x < 0) {
37 return 0;
38 }
39
40 int factorial = 1;
41
42 while (x > 1) {
43 factorial = factorial * x;
44 x = x - 1;
45 }
46
47 return factorial;
48 }
49
50 public static double format(double x, int max, int min) {
51 NumberFormat nf = NumberFormat.getInstance();
52
53 nf.setMaximumFractionDigits(max);
54 nf.setMinimumFractionDigits(min);
55
56 try {
57 Number number = nf.parse(nf.format(x));
58
59 x = number.doubleValue();
60 }
61 catch (Exception e) {
62 _log.error(e.getMessage());
63 }
64
65 return x;
66 }
67
68 public static boolean isEven(int x) {
69 if ((x % 2) == 0) {
70 return true;
71 }
72
73 return false;
74 }
75
76 public static boolean isOdd(int x) {
77 return !isEven(x);
78 }
79
80 public static int[] generatePrimes(int max) {
81 if (max < 2) {
82 return new int[0];
83 }
84 else {
85 boolean[] crossedOut = new boolean[max + 1];
86
87 for (int i = 2; i < crossedOut.length; i++) {
88 crossedOut[i] = false;
89 }
90
91 int limit = (int)Math.sqrt(crossedOut.length);
92
93 for (int i = 2; i <= limit; i++) {
94 if (!crossedOut[i]) {
95 for (int multiple = 2 * i; multiple < crossedOut.length;
96 multiple += i) {
97
98 crossedOut[multiple] = true;
99 }
100 }
101 }
102
103 int uncrossedCount = 0;
104
105 for (int i = 2; i < crossedOut.length; i++) {
106 if (!crossedOut[i]) {
107 uncrossedCount++;
108 }
109 }
110
111 int[] result = new int[uncrossedCount];
112
113 for (int i = 2, j = 0; i < crossedOut.length; i++) {
114 if (!crossedOut[i]) {
115 result[j++] = i;
116 }
117 }
118
119 return result;
120 }
121 }
122
123 private static Log _log = LogFactoryUtil.getLog(MathUtil.class);
124
125 }