I want to receive advice on my code. It is too slow... The problem I am trying to solve is:
What is the value of the first triangle number to have over five hundred divisors?
import math
import numpy as np
import copy
from operator import add
memoi_table = {}
#check whether the x is prime or not
#to do a prime factorization
def prime_finder(x):
cnt = 0
a = math.sqrt(x)
sqrt_number = int(math.floor(a))
for i in range(2,sqrt_number+1):
if x % i == 0:
cnt = cnt +1
break
if cnt == 0:
return True
else:
return False
#Do a prime_factorization
#Do a dynamic programing with memoization table
#Do a recursive method to cover the triangular number
#ex)Triangular number = 1,3,6,10,15,21,28
#When we treat 10, we couldn't utilize dynamic programming => Recursive method
def prime_factorization(x):
global memoi_table
memoi_table[x] = {}
if prime_finder(x) == True:
memoi_table[x][x] = 1
for i in range(2,math.floor(math.sqrt(x)+1)):
if (prime_finder(i) == True) and (x % i == 0):
new_x = x / i
if not new_x in memoi_table.keys():
prime_factorization(new_x)
#Recursive way
if new_x in memoi_table.keys():
memoi_table[x] = memoi_table[new_x].copy()
#to shallow copy
if i in memoi_table[x].keys():
memoi_table[x][i] = memoi_table[x][i] + 1
else:
memoi_table[x][i] = 1
return (x,memoi_table[x])
#ex) 20 => return (20,(2:2,5:1))
# To calculate the number of divisor based on prime factorization
def find_number_of_divisor(x):
global memoi_table
number_of_divisor = 1
for key in memoi_table[x].keys():
number_of_divisor = number_of_divisor * (memoi_table[x][key]+1)
return number_of_divisor
#Let's do it
def main():
global memoi_table
n = 0
while True:
n = n + 1
Triangular_number = n * (n + 1) / 2
prime_factorization(Triangular_number)
num_divisor = find_number_of_divisor(Triangular_number)
if num_divisor > 500:
return (Triangular_number,num_divisor)
break
print(main())