Java的:304 260 257
我通过稍微压缩备忘录功能f(n)
并将其完全删除,用直接数组访问代替了它,从而节省了一些字节。
BigInteger[]c;BigInteger a(int n,int k){m(n);return g(n).divide(g(n-k)).divide(g(k));}BigInteger g(int n){return n<3?BigInteger.ONE:g(n-1).multiply(c[n-1]);}void m(int n){c=new BigInteger[n];for(int i=0;i<n;++i)c[i]=(i<2)?BigInteger.ONE:c[i-2].add(c[i-1]);}
不幸的是,BigInteger
由于溢出而被要求,我不得不添加备忘录。即使在第6代i7上,的方式太长,大投入运行。
取消高尔夫,带有样板class
和main
代码:
import java.math.BigInteger;
public class ComputeTheFibonomialCoefficient {
public static void main(final String[] args) {
// @formatter:off
String[][] testData = new String[][] {
{ "0", "0", "1" },
{ "1", "1", "1" },
{ "2", "0", "1" },
{ "3", "2", "2" },
{ "8", "3", "1092" },
{ "11", "5", "1514513" },
{ "22", "7", "7158243695757340957617" },
{ "25", "3", "49845401197200" },
{ "50", "2", "97905340104793732225" },
{ "100", "1", "354224848179261915075" }
};
// @formatter:on
for (String[] data : testData) {
System.out.println("a(" + data[0] + ", " + data[1] + ")");
System.out.println(" Expected -> " + data[2]);
System.out.print(" Actual -> ");
System.out.println(new ComputeTheFibonomialCoefficient().a(
Integer.parseInt(data[0]), Integer.parseInt(data[1])));
System.out.println();
}
}
// Begin golf
BigInteger[] c;
BigInteger a(int n, int k) {
m(n);
return g(n).divide(g(n - k)).divide(g(k));
}
BigInteger g(int n) {
return n < 3 ? BigInteger.ONE : g(n - 1).multiply(c[n - 1]);
}
void m(int n) {
c = new BigInteger[n];
for (int i = 0; i < n; ++i)
c[i] = (i < 2) ? BigInteger.ONE : c[i - 2].add(c[i - 1]);
}
// End golf
}
程序输出:
a(0, 0)
Expected -> 1
Actual -> 1
a(1, 1)
Expected -> 1
Actual -> 1
a(2, 0)
Expected -> 1
Actual -> 1
a(3, 2)
Expected -> 2
Actual -> 2
a(8, 3)
Expected -> 1092
Actual -> 1092
a(11, 5)
Expected -> 1514513
Actual -> 1514513
a(22, 7)
Expected -> 7158243695757340957617
Actual -> 7158243695757340957617
a(25, 3)
Expected -> 49845401197200
Actual -> 49845401197200
a(50, 2)
Expected -> 97905340104793732225
Actual -> 97905340104793732225
a(100, 1)
Expected -> 354224848179261915075
Actual -> 354224848179261915075
1335
了斐波南系数的顺序中的第一个值。