Euler Problem 44

Pentagonal numbers are generated by the formula, P_(n)=n(3n−1)/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.

  1. Use the standard quadratic equation on P_(n)=n(3n−1)/2 to flip it. This way you can go both ways when needed. Check out Pentagonal Numbers on Wiki.
  2. 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;
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s