Num Py Project Euler 3
Num Py Project Euler 3
net
We can apply the factorization recursively, until we get the required prime factors.
3. Find 0 fractions
Call the NumPy where function to find the indices of 0 fractions.
indices = numpy.where(fractions == 0)
def factor(n): #1. Create array of trial values a = numpy.ceil(numpy.sqrt(n)) lim = min(n, LIM) a = numpy.arange(a, a + lim) b2 = a ** 2 - n #2. Check whether b is a square fractions = numpy.modf(numpy.sqrt(b2))[0] #3. Find 0 fractions indices = numpy.where(fractions == 0) #4. a = a = b = b = c = d = Find the first occurrence of a 0 fraction numpy.ravel(numpy.take(a, indices))[0] int(a) numpy.sqrt(a ** 2 - n) int(b) a + b a - b
Have a go
I would suggest writing an unit test to check the outcome. Use for example trial division. To get you started here is some of the code of a possible test function. Please fill in the dots.
def is_prime(n): a = numpy.arange(2, n) return len(a[...]) == 0
Also maybe you should try finetuning the size of the trial values array, but be careful. If you liked this post and are interested in NumPy check out NumPy Beginners Guide by yours truly.