Pentagonal numbers made from pentagonal numbers
CJam, 29 bytes
6e5{)_3*(*2/}%_A4#<riew::+&1<
Try it online.
Takes a couple of seconds to run.
Explanation
First, we need to check how many pentagonal numbers we need to consider as potential sums. The sum of the first 10,000 pentagonal numbers is 500050000000
. The first pentagonal number greater than that is the 577,380th.
6e5 e# 600,000 (a short number that's a bit bigger than we need).
{ e# Map this block onto every number from 0 to 599,999...
) e# Increment.
_3*(*2/ e# Apply the pentagonal number formula given in the challenge.
}%
_ e# Make a copy.
A4#< e# Truncate to the first 10,000 elements.
ri e# Read input and convert to integer.
ew e# Get sublists of that length.
::+ e# Sum each sublist.
& e# Set intersection with all 600k pentagonal numbers computed earlier.
1< e# Truncate to the first result.
I used a slightly modified program to find the largest inputs which yield a non-empty solution. These are all the solutions for inputs greater than 9,000:
9919 -> 496458299155
9577 -> 446991927537
9499 -> 455533474060
9241 -> 401702906276
9017 -> 429351677617
Lua, 142 Bytes
p={}o={}n=...for i=1,10^4 do p[i]=(3*i^2-i)/2o[p[i]]=1 end for i=0,10^4-n do s=0 for j=1,n do s=s+p[i+j]end if(o[s])then print(s)break end end
Ungolfed
p={}o={}n=tonumber(...)
for i=1,10^4 do
p[i]=(3*i^2-i)/2o[p[i]]=1
end
for i=0,10^4-n do
s=0
for j=1,n do
s=s+p[i+j]
end
if(o[s])then
print(s)
break
end
end
Yay for inverting tables!
Update 142 Bytes: Saved 10 bytes by removing superfluous 'tonumber' function call.
Haskell, 109 bytes
p=map(\n->div(3*n^2-n)2)[1..10^7]
(%)=(sum.).take
x#l|length l<x=0|elem(x%l)p=x%l|1<2=x#tail l
(#take(10^4)p)
Returns 0
if there's no pentagonal pentagon number.
Usage example (takes some time to finish): map (#take(10^4)p) [1..10]
-> [1,1926,0,330,44290,651,287,0,12105,0]
.
It's more or less a direct implementation of the definition: if the sum of the first x
elements is in the list, output it, else re-try with the tail of the list. Start with the first 10,000 pentagonal numbers, stop and return 0
if the list has less than x
elements.