Search code examples
pythonfloating-pointintfactorization

Explain the float - int problem in factorization


I am missing here the technical word but the problem here is either to change int to float or float to int.

def factorize(n):
    def isPrime(n):
        return not [x for x in range(2,int(math.sqrt(n)))
                    if n%x == 0]
    primes = []
    candidates = range(2,n+1)
    candidate = 2
    while not primes and candidate in candidates:
        if n%candidate == 0 and isPrime(candidate):

            # WHY ERROR?
            #I have tried here to add float(), int() but cannot understand why it returns err
            primes = primes + [float(candidate)] + float(factorize(n/candidate))
        candidate += 1
    return primes

The err -- tried fixing it with functions such as int() and float() but still persist:

TypeError: 'float' object cannot be interpreted as an integer

Solution

  • This expression is your immediate problem:

    float(factorize(n/candidate))
    

    factorize returns a list, but float needs its argument to be a string or a number.

    (Your code has many, many other problems but perhaps it would be best for you to discover them for yourself...)