<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
//对于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
相关文章推荐
- <MEMORY>Project Euler NO33
- <MEMORY>Project Euler NO27
- <MEMORY>Project Euler NO28
- <MEMORY>Project Euler NO52
- <MEMORY>Project Euler NO23
- <MEMORY>Project Euler NO29
- <MEMORY>Project Euler NO45
- <MEMORY>Project Euler NO24
- <MEMORY>Project Eul 4000 er NO30
- <MEMORY>Project Euler NO39
- <MEMORY>Project Euler NO46
- <MEMORY>Project Euler NO20
- <MEMORY>Project Euler NO21
- <MEMORY>Project Euler NO47
- <MEMORY>Project Euler NO41
- <MEMORY>Project Euler NO26
- <MEMORY>Project Euler NO49
- <MEMORY>Project Euler NO57
- <MEMORY>Project Euler NO13
- <MEMORY>Project Euler NO32