Pentagonal numbers are generated by the formula, P

_{n}=n(3n1)/2. The first ten pentagonal numbers are:1, 5, 12, 22, 35, 51, 70, 92, 117, 145, …

It can be seen that P

_{4}+ P_{7}= 22 + 70 = 92 = P_{8}. However, their difference, 70 22 = 48, is not pentagonal.Find the pair of pentagonal numbers, P

_{j}and P_{k}, for which their sum and difference is pentagonal and D = |P_{k}P_{j}| is minimised; what is the value of D?

It seems simple … and it is, providing you do two things.

- Use the standard quadratic equation on P
_{n}=`n`(3`n`1)/2 to flip it. This way you can go both ways when needed. Check out Pentagonal Numbers on Wiki. - ALWAYS CHECK YOUR FORMULAS! I spent days and many wrong submissions because one of my formulas was wrong..

public class Euler44

{

public static void main(String[] args)

{

Euler44 e = new Euler44();

System.out.format(“Problem: %s\n”, e.getClass().getName());

System.out.format(“Answer = %s\n”, e.Problem());

}

public String Problem ()

{

long max = Long.MAX_VALUE;

for (long j = 1; j <= 10000; j++)

for (long k = 1; k <= j; k++)

if (isPent(P(j)+P(k)) && isPent(P(j)-P(k)))

if (P(j)-P(k) < max)

max = P(j)-P(k);

return String.valueOf(max);

}

public boolean isPent (long n)

{

if ((Math.sqrt(1+24*n)+1) % 6 == 0)

return true;

return false;

}

public long P (long n)

{

return n*(3*n-1)/2;

}

}