I am trying to write a script that determines whether it is possible to factorize an integer value in a list of integers. The way I have done it is to search recursivley for a valid factorization, effectiveley doing a DFS in a tree of possible factors (in the code below). Is it possible to make a greedy algorithm that finds this fast? My idea was to keep searching the list for the largest factor in the remainder until a valid factorization is found. Will that be a correct algorith in this case? If not, is this problem in NP?
Code to solve the problem written in Python:
def can_factorize_in_list(n, list):
# Determines whether it is possible to factorize 'n' in 'list'
# Filter the list to only include the values which are factors
fac_list = [p for p in list if (n % p is 0)]
for x in fac_list:
if n % x is 0:
if n/x is 1:
# If we end up at 1, we have a valid factorization
return 1 # End state
else:
# If we do not end at 1, keep trying
if can_factorize_in_list(n/x, fac_list):
return 1
else:
continue
return 0
EDIT: For instance, given integer 30 and list [2,3,5,8], the algorithm should return True because 30 = 2*3*5. It is not required to use all the elements in the list as factors and factors can be used more than once.