Reputation: 1897
I've created a function which, hopefully, creates a list of numbers that are both pentagonal and square.
Here is what i've got so far:
def sqpent(n):
i = 0
list = []
while n >= 0:
if n == 0:
list.append(0)
elif n == 1:
list.append(1)
elif (i*i == (i*(3*i-1)//2)):
list.append(i)
n -= 1
i += 1
But when it gets past the first two numbers it seems to be taking a while to do so...
Upvotes: 1
Views: 295
Reputation: 1897
Thanks to @interjay's advice, I came up with this answer which works perfectly:
import math
def sqpent(n):
counter = 0
i = 0
l = []
while counter < n:
x = (i*(3*i-1)//2)
#print(x)
if(int(math.sqrt(x))**2 == x):
#print("APPENDED: " + str(x))
l.append(x)
counter += 1
i += 1
return l
For an explanation:
Upvotes: 0
Reputation: 110108
You have two issues: the first is that the special-casing for n==0
and n==1
doesn't decrease n
, so it goes into an infinite loop. The special-casing isn't really needed and can be dropped.
The second, and more significant one, is that in the test i*i == (i*(3*i-1)//2)
you are assuming that the index i
will be the same for the square and pentagonal number. But this will only happen for i==0
and i==1
, so you won't find values past that.
I suggest:
i
instead of n
to make things simpler.i
th pentagonal number and check if it is a square number (e.g. int(sqrt(x))**2 == x
).n
numbers.Upvotes: 2