I wrote and use this function to create prime number factors:
import numpy as np from math import sqrt def primesfrom3to(n): """ Returns a array of primes, p < n """ assert n>=2 sieve = np.ones(n/2, dtype=np.bool) for i in xrange(3,int(n**0.5)+1,2): if sieve[i/2]: sieve[i*i/2::i] = False return np.r_[2, 2*np.nonzero(sieve)[0][1::]+1] def primefactors(tgt,verbose=True): if verbose: print '\n\nFinding prime factors of: {:,}'.format(tgt) primes=primesfrom3to(sqrt(tgt)+1) if verbose: print ('{:,} primes between 2 and square root of tgt ({:.4})'. format(len(primes),sqrt(tgt))) return [prime for prime in primes if not tgt%prime]
If I call it Project Euler # 3 , it successfully creates a list of different prime numbers:
>>> print primefactors(600851475143) Finding prime factors of: 600,851,475,143 62,113 primes between 2 and square root of tgt (7.751e+05) [71, 839, 1471, 6857]
This is consistent with what Wolfram Alpha produces for key factors. (And the biggest is the correct answer to Project Euler # 3)
Now let's say that I want the factors of this number x 1e6:
>>> print primefactors(600851475143*1000000) Finding prime factors of: 600,851,475,143,000,000 39,932,602 primes between 2 and square root of tgt (7.751e+08) [2, 5, 71, 839, 1471, 6857]
For this more Wolfram Alpha produces :
2**6 * 5**6 * 71 * 839 * 1471 * 6857
Is there an easy way to change my code, which I can calculate the values ββof 2 and 5 as the main factors of a larger number?
(I'm interested in the source code or the algorithm for this - not a pointer to a library that will do this for me, thanks!)