vendredi 24 juin 2016

Improve recursive algorithm for finite products of primes

From the book How to Read and Do Proofs by Daniel Solow, I took the following problem:

Any integer n >= 2 can be expressed as a finite product of primes.

After looking at the proof by induction in the book, I tried then to implement an algorithm to verify it:

 from fermat import fermat

def first_prime_divisor(n, j):
    if not fermat(j):
        return first_prime_divisor(n, j+1)
    else:
        if n%j:
            return first_prime_divisor(n, j+1)
        else:
            return j

def products(n, lista):


    if n == 2:
        lista.append(2)
    elif fermat(n):
        lista.append(n)
    else:
        num = first_prime_divisor(n, 2)
        lista.append(num)
        products(n//num, lista)

Where fermat is a known primality test. The code works fine and changes the state of the inputed list accordingly. There are two problems though:

1) I'd like not to have a list variable and instead the function itself returning it to me

2) The code doesn't work for large number (not so large, e.g, 1531351254251) because it run out of memory first.

Could you give suggestions for fixing it?

PS: I'm trying to improve my way of reasoning about recursion, so I've solved the problem using it.

Aucun commentaire:

Enregistrer un commentaire