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