#!/usr/bin/env python ''' Created on 21 oct. 2012 @author: Julien Lengrand-Lambert DESCRIPTION: Solves problem 44 of Project Euler 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? ''' penta_vals = [] def is_pentagonal(val): """ Returns True if val is a pentagonal number """ global penta_vals return (val in penta_vals) def pent(val): """ Returns the pentagonal number created using val Pentagonal numbers are defined by Pn=n(3n-1)/2 """ return (val * (3 * val - 1) / 2) def create_pentagonal(ite=1000): """ Returns a list of ite pentagonal numbers default is 1000 Pentagonal numbers are defined by Pn=n(3n1)/2 """ temp = range(1, ite + 1) return [pent(val) for val in temp] def find_pair(ite=1000): """ Finds the pair of pentagonal numbers such as Pj + Pk and Pj - Pk are also pentagonal Returns minimised |Pk - Pj| """ global penta_vals penta_vals = create_pentagonal(ite) for val_j in penta_vals: for val_k in penta_vals: if is_pentagonal(val_k + val_j) and is_pentagonal(val_k - val_j): return min(abs(val_j - val_k), abs(val_k - val_j)) if __name__ == '__main__': print "Answer : %d " % (find_pair(10000)) # 10000 is just a rude guess