Java用数组求奇数阶乘并格式化输出。

200以内的奇数阶乘,详细的baiduHi,不能用BigDecemial

public class Factorial {
private int[] date = new int[100000];

private int weishu = 1;

public String factorial(int n) {
String result = "";
date[1] = 1;
for (int i = 1; i <= n; i = i + 2) {
for (int j = 1; j <= weishu; j++) {
date[j] = date[j] * i;
}

for (int j = 1; j < weishu; j++) {
if (date[j] >= 10) {
date[j + 1] += date[j] / 10;
date[j] = date[j] % 10;
}
}
while (date[weishu] >= 10) {
weishu++;
date[weishu] += date[weishu - 1] / 10;
date[weishu - 1] = date[weishu - 1] % 10;
}
}
for (int k = weishu; k >= 1; k--) {
result = result + date[k];
}
return format(result, 4, " ");
}

public String format(String str, int num, String mark) {
// mark为分位符标记
List ls = new ArrayList();
String result = "";
List list = new ArrayList();
int i = 0;
if (str.length() % num != 0) {
i = str.length() % num;
ls.add(str.substring(0, str.length() % num) + mark);
}
for (; i < str.length(); i += num) {
if (i < str.length() - 4) {
ls.add(str.substring(i, i + num) + mark);
} else {
ls.add(str.substring(i, str.length()));
}
}
i = 0;
if (ls.size() % 5 != 0) {
i = ls.size() % 5;
String temp = "";
for (int j = 0; j < i; j++) {
temp = temp + ls.get(j);
}
list.add(temp + "\n");
}
for (; i < ls.size(); i += 5) {
String temp = (String) ls.get(i) + ls.get(i + 1) + ls.get(i + 2)
+ ls.get(i + 3) + ls.get(i + 4);
list.add(temp + "\n");
}
while (temp.length() <= 50) {
temp = " " + temp;
}
list.set(0, temp);
for (int j = 0; j < list.size(); j++) {
result = result + list.get(j);
}
return result;

}

public static void main(String[] args) {
System.out.println(new Factorial().factorial(46));
}
}
温馨提示:答案为网友推荐,仅供参考
相似回答