7,765
社区成员
发帖
与我相关
我的任务
分享
static System.Numerics.BigInteger Factorial(System.Numerics.BigInteger i)
{
if (i.IsZero || i.Sign == -1)
return System.Numerics.BigInteger.Zero;
if (i.IsOne)
return System.Numerics.BigInteger.One;
else
return i * Factorial(i - 1);
}
static void Main(string[] args)
{
if (args.Length < 1)
return;
int i;
if (int.TryParse(args[0], out i))
{
System.Numerics.BigInteger bi = i;
System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew();
bi = Factorial(bi);
sw.Stop();
//计算结果太长,只输出结果长度
Console.Write("结果长度:{0} 用时:{1}", bi.ToString().Length, sw.Elapsed);
}
}
static System.Numerics.BigInteger Factorial(System.Numerics.BigInteger i)
{
System.Numerics.BigInteger result = 1;
while (true)
{
if (i < 2)
return result;
result *= i;
i--;
}
}
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class F {
static final int cnt = Runtime.getRuntime().availableProcessors() * 4;
static final ExecutorService threadPool = Executors.newFixedThreadPool(cnt);
public static void main(String[] args) throws Exception {
int[] tests = new int[] {
9999, 15000, 20000, 99999
};
for (int i : tests) {
long start = System.currentTimeMillis();
BigInteger result = f(i);
long end = System.currentTimeMillis();
System.out.printf("结果长度:%s 用时:%s\n", result.toString().length(), end
- start);
}
threadPool.shutdown();
}
public static BigInteger f(final int n) throws Exception {
List<Callable<BigInteger>> taskList = new ArrayList<Callable<BigInteger>>();
for (int i = 1; i <= cnt; i++) {
final int threadNo = i;
Callable<BigInteger> task = new Callable<BigInteger>() {
public BigInteger call() {
BigInteger result = BigInteger.ONE;
for (int j = threadNo; j <= n; j += cnt) {
result = result.multiply(BigInteger.valueOf(j));
}
return result;
}
};
taskList.add(task);
}
List<Future<BigInteger>> futureList = threadPool.invokeAll(taskList);
BigInteger f = BigInteger.ONE;
for (Future<BigInteger> future : futureList) {
f = f.multiply(future.get());
}
return f;
}
}
等待高人