이경수 선생님의 수학실험실

Problem 44(Pentagon numbers) 본문

Project Euler

Problem 44(Pentagon numbers)

(이경수) 2019. 7. 24. 18:18

Problem 44(Pentagon numbers)

Pentagonal numbers are generated by the formula, \(P_{n}=\frac{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 are pentagonal and \(D = |P_{k} − P_{j}|\) is minimised; what is the value of \(D\)?

 

In Python:

import time
import math

startTime = time.time()
diffList = []
for i in range(1, 10 ** 4):
    val1 = 0
    for j in range(0, 10 ** 4):
        val1 += 3 * (i + j) + 1
        if math.sqrt(1 + 24 * val1) % 6 == 5:
            val2 = i * (3 * i - 1) + val1
            if math.sqrt(1 + 24 * val2) % 6 == 5:
                diffList.append(val1)
print(min(diffList))
print(time.time() - startTime, "seconds")

Run time: 59.95046591758728 seconds

 

In Python:

import time

startTime = time.time()
i = 2
check = 0
pentagonList = [1]

while True:
    pentagon = i * (3 * i - 1) // 2
    for j in pentagonList:
        k = pentagon - j
        if k in pentagonList:
            if abs(j - k) in pentagonList:
                print(abs(j - k));
                check = 1
                break
    pentagonList.append(pentagon)
    if check == 1:
        break
    i += 1
print(time.time() - startTime, "seconds")

Run time: 59.71640586853027 seconds

 

In Python:

import time
import math

def ispentagon(n):
    if math.sqrt(1 + 24 * n) % 6 == 5:
        return True
    else:
        return False

startTime = time.time()
i = 2
check = 0
pentagonList = [1]

while True:
    pentagon = i * (3 * i - 1) // 2
    for j in pentagonList:
        k = pentagon - j
        if ispentagon(k) and ispentagon(abs(j - k)):
                print(abs(j - k));
                check = 1
                break
    if check:
        break
    else:
        pentagonList.append(pentagon)
        i += 1
print(time.time() - startTime, "seconds")

Run time: 1.6193530559539795 seconds

 

Solution: 5482660

Comments