基于BigInteger的多线程计算阶乘的各位数字和
2018-11-30 本文已影响45人
ZeroForSpider
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.stream.Collector;
import java.util.stream.Collectors;
class FactorialSum implements Callable<BigInteger> {
private int startNumber;
private int endNumber;
public FactorialSum(int startNumber, int endNumber) {
this.startNumber = startNumber;
this.endNumber = endNumber;
}
public BigInteger factorial() {
BigInteger factorialResult = new BigInteger("1");
BigInteger bigIntegerEnd=new BigInteger(String.valueOf(endNumber));
int count=endNumber-startNumber;
BigInteger step=new BigInteger("1");
while (count>=0){
factorialResult=factorialResult.multiply(bigIntegerEnd);
bigIntegerEnd=bigIntegerEnd.subtract(step);
count--;
}
return factorialResult;
}
@Override
public BigInteger call() throws Exception {
return factorial();
}
public static String factorialSum(String number) {
char[] chars = number.toCharArray();
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < chars.length; i++) {
list.add(chars[i] - '0');
}
return String.valueOf(list.stream().collect(Collectors.summarizingInt(m -> m)).getSum());
}
public static String createThread(int number) throws ExecutionException, InterruptedException {
if (number >= 50) {
int average = number / 4;
FutureTask<BigInteger> thread1 = new FutureTask<BigInteger>(new FactorialSum(1, average));
new Thread(thread1).start();
FutureTask<BigInteger> thread2 = new FutureTask<BigInteger>(new FactorialSum(average + 1, average * 2));
new Thread(thread2).start();
FutureTask<BigInteger> thread3 = new FutureTask<BigInteger>(new FactorialSum(average * 2 + 1, average * 3));
new Thread(thread3).start();
FutureTask<BigInteger> thread4 = new FutureTask<BigInteger>(new FactorialSum(average * 3 + 1, number));
new Thread(thread4).start();
return thread1.get().multiply(thread2.get()).multiply(thread3.get()).multiply(thread4.get()).toString();
} else {
FutureTask<BigInteger> thread1 = new FutureTask<BigInteger>(new FactorialSum(1, number));
new Thread(thread1).start();
return thread1.get().toString();
}
}
}
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
long startTime = System.currentTimeMillis();
System.out.println(FactorialSum.factorialSum(FactorialSum.createThread(Integer.valueOf(args[0]))));
System.out.println("times:" + (System.currentTimeMillis() - startTime));
}
}
运行结果如下:
image.png