0

I wrote a program about triangular numbers, which are derived from the sum of natural numbers one after the other. For example, the third triangular number is equal to: 1 + 2 + 3 = 6. NOW I WANT to find Divisors of triangular numbers. for example the third triangular number have 4 divisors which equal to : 1,2,3,6 so I want to find the first number which have more than 500 divisors . program working fine but slow so I don't get an answer . what's your opinion for optimize my program? some triangular number Whith their divisors: (1: 1) , (3: 1,3) , (6: 1,2,3,6) , (10: 1,2,5,10) , (15: 1,3,5,15) , (21: 1,3,7,21) , (28: 1,2,4,7,14,28)

def triangular(n):
    a= []
    for i in range (2,n):
        if n % i == 0 :
            a.append(i)
    if len(a) > 498:
        return True
    else :
        a.clear()
        return False
x=1
n=x
while x>0:
    if triangular(n):
        print(n)
        break
    else:
        n+=x+1
        x+=1
Mohsen.RJ
  • 344
  • 1
  • 11
  • If you have working code and you're looking for improvements, you should post on https://codereview.stackexchange.com/ instead – Mike Scotty Jan 25 '21 at 08:38

1 Answers1

0

Now, I adapted some code I found here which works very fast to find how many divisors a number has, so this should work much much quicker than your current solution:

import operator
import functools


def PrimesPlus():
    """Superset of primes"""

    yield 2
    yield 3
    i = 5
    while True:
        yield i
        if i % 6 == 1:
            i += 2
        i += 2


def GetPrimeDecomp(n):
    """Returns a dict d with n = product p ^ d[p]"""

    d = {}
    primes = PrimesPlus()
    for p in primes:
        while n % p == 0:
            n /= p
            d[p] = d.setdefault(p, 0) + 1
        if n == 1:
            return d


def NumberOfDivisors(n):
    """Returns how many divisors a number has"""
    d = GetPrimeDecomp(n)
    powers_plus = map(lambda x: x + 1, d.values())
    return functools.reduce(operator.mul, powers_plus, 1)

if __name__ == "__main__":
    x = 1
    n = 1
    while x > 0:
        if NumberOfDivisors(n) > 500:
            print(n)
            break
        else:
            x += 1
            n += x
Rolv Apneseth
  • 2,078
  • 2
  • 7
  • 19