利用以下的公式可以测试一个正整数x是否是五边形数
五角数通过如下公式定义:Pn=n(3n1)/2。前十个五角数是:
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
可以看出P4 + P7 = 22 + 70 = 92 = P8. 但是它们的差70 22 = 48却不是五角数。
找出最小的五角数对Pj 和 Pk,, 使得它们的和与差都是五角数,并且D = |Pk Pj| 取到最小。这时D的值是多少?
public class Problem44
{
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()
{
l1: for (int i = 2;; i++)
{
l2 : for (int j = i - 1; j > 0; j--)
{
int t1 = i * (3 * i - 1) / 2;
int t2 = j * (3 * j - 1) / 2;
int add = t1 + t2;
int subtration = t1 - t2;
double tempadd = (Math.sqrt(24 * add + 1) + 1) / 6;
double tempsub = (Math.sqrt(24 * subtration + 1) + 1) / 6;
if ((int)tempadd != tempadd)
{
continue l2;
}
if ((int)tempsub != tempsub)
{
continue l2;
}
System.out.println(subtration);
break l1;
}
}
}
}
answer: 5482660
time: 67