您的位置:首页 > 其它

<MEMORY>Project Euler NO15

2014-01-21 22:37 375 查看
//从一个2×2网格的左上角开始,有6条(不允许往回走)通往右下角的路。
//对于20×20的网格,这样的路有多少条?

遍历法15 * 15 的网格需要花费3秒以上,故不能使用!!

import java.math.BigInteger;

public class Problem15
{

static int n = 20;
public static void main(String[] args)
{
long start = System.currentTimeMillis();
System.out.print("answer: ");
howmany();
long end = System.currentTimeMillis();
System.out.print("time: ");
System.out.println(end - start);
}

static void howmany()
{
BigInteger s = BigInteger.valueOf(1);
for (int i = 1; i <= 2 * n; i++)
{
s = s.multiply(BigInteger.valueOf(2));
}
for (int i = 2 * n; i > n; i--)
{
s = s.add(BigInteger.valueOf(2).multiply( CMN(2 * n, i)).negate());
}

System.out.println(s);
}

static BigInteger CMN(int m, int n)
{
BigInteger s1 = BigInteger.ONE;
BigInteger s2 = BigInteger.ONE;
for (int i = m; i > m - n; i--)
{
s1 = s1.multiply(BigInteger.valueOf(i));
}

for (int i = 2; i <= n; i++)
{
s2 = s2.multiply(BigInteger.valueOf(i));
}
return s1.divide(s2);
}

}

answer:  137846528820

time:  5
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  PE