當前位置:編程學習大全網 - 編程語言 - Java用數組求奇數階乘並格式化輸出。

Java用數組求奇數階乘並格式化輸出。

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));

}

}

  • 上一篇:皮膚碼不能用,怎麽回事?
  • 下一篇:網絡工程師需要什麽專業知識和資格證書
  • copyright 2024編程學習大全網