Project Euler #88: Product-sum numbers

  • + 0 comments
    Python
    def valid(n: int, k: int) -> bool:
        if k > limit:
            return False
        if minK[k] > n:
            minK[k] = n
            return True
        return False
        
    def getMinK(n: int, product: int, summ: int, depth: int = 1, factor: int = 2) -> int:
        if product == 1:
            return 1 if valid(n, depth + summ - 1) else 0
        
        res = 0
        if depth > 1:
            if product == summ:
                return 1 if valid(n, depth) else 0
            
            if valid(n, depth + summ - product):
                res += 1
        
        for i in range(factor, int(product ** .5) + 1):
            if product % i == 0:
                res += getMinK(n, product // i, summ - i, depth + 1, i)
                
        return res
    
    limit = int(input())
    minK = [9999999] * (limit + 1)
    
    n, summ, i = 4, 0, 1
    while i < limit:
        cnt = getMinK(n, n, n)
        if cnt > 0:
            i += cnt
            summ += n
        n += 1
    
    print(summ)