#### Overview of this book

Today's world of science and technology is all about speed and flexibility. When it comes to scientific computing, NumPy is on the top of the list. NumPy will give you both speed and high productivity. "NumPy Cookbook" will teach you all about NumPy, a leading scientific computing library. NumPy replaces a lot of the functionality of Matlab and Mathematica, but in contrast to those products, it is free and open source. "Numpy Cookbook" will teach you to write readable, efficient, and fast code that is as close to the language of Mathematics as much as possible with the cutting edge open source NumPy software library. You will learn about installing and using NumPy and related concepts. At the end of the book, we will explore related scientific computing projects. This book will give you a solid foundation in NumPy arrays and universal functions. You will also learn about plotting with Matplotlib and the related SciPy project through examples. "NumPy Cookbook" will help you to be productive with NumPy and write clean and fast code.
NumPy Cookbook
Credits
www.PacktPub.com
Preface
Free Chapter
Winding Along with IPython
Get to Grips with Commonly Used Functions
Connecting NumPy with the Rest of the World
Audio and Image Processing
Special Arrays and Universal Functions
Profiling and Debugging
Quality Assurance
Speed Up Code with Cython
Index

## Finding prime factors

Prime factors (http://en.wikipedia.org/wiki/Prime_factor) are prime numbers that divide an integer exactly without a remainder. Finding prime factors seems almost impossible to crack. However, using the right algorithm—Fermat's factorization method (http://en.wikipedia.org/wiki/Fermat%27s_factorization_method) and NumPy—it becomes very easy. The idea is to factor a number N into two numbers c and d, according to the following equation:

We can apply the factorization recursively, until we get the required prime factors.

### How to do it...

The algorithm requires us to try a number of trial values for `a`.

1. Create an array of trial values.

It makes sense to create a NumPy array and eliminate the need for loops. However, you should be careful to not create an array that is too big in terms of memory requirements. On my system, an array of a million elements seems to be just the right size:

```a = numpy.ceil(numpy.sqrt(n))
lim = min(n, LIM)
a = numpy.arange(a, a + lim)
b2 = a ** 2 - n```

We...