Project Euler

Project Euler Problem 44

steloflute 2012. 6. 9. 00:11

Problem 44

23 May 2003

Pentagonal numbers are generated by the formula, Pn=n(3n1)/2. The first ten pentagonal numbers are:

1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...

It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 22 = 48, is not pentagonal.

Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference is pentagonal and D = |Pk Pj| is minimised; what is the value of D?


Answer:
5482660

 

 

C#

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;

namespace Euler {
    class Program {
        static bool isPentagonal(int value) {
            var index = (Math.Sqrt(24 * value + 1) + 1) / 6;
            return index == (int)index;
        }

        static void Main(string[] args) {
            var pentagonals = new HashSet<int>();
            for (var i = 1; ; i++) {
                var c = i * (3 * i - 1) / 2;
                foreach (var p in pentagonals) {
                    var sum = c + p;
                    var diff = c - p;
                    if (isPentagonal(sum) && isPentagonal(diff)) {
                        Console.WriteLine(diff);
                        Environment.Exit(0);
                    }
                }
                pentagonals.Add(c);
            }
        }
    }
}



'Project Euler' 카테고리의 다른 글

Project Euler Problem 46  (0) 2012.06.09
Project Euler Problem 45  (0) 2012.06.09
Project Euler Problem 43  (0) 2012.06.09
Project Euler Problem 42  (0) 2012.06.09
Project Euler Problem 41  (0) 2012.06.09