madcrazydrumma
madcrazydrumma

Reputation: 1897

Calculating Polygonal Numbers Taking A While To Calculate

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

Answers (2)

madcrazydrumma
madcrazydrumma

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:

  • It iterates through a value i, and gets the ith pentagonal number. Then it checks if it is a square and if so it appends it to a list which i ultimately return.
  • It does this until a final point when the counter reaches the number of items in the list you want.

Upvotes: 0

interjay
interjay

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:

  1. Iterate over i instead of n to make things simpler.
  2. Take the ith pentagonal number and check if it is a square number (e.g. int(sqrt(x))**2 == x).
  3. Stop when you've reached n numbers.

Upvotes: 2

Related Questions