Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
NumPy Cookbook

You're reading from  NumPy Cookbook

Product type Book
Published in Oct 2012
Publisher Packt
ISBN-13 9781849518925
Pages 226 pages
Edition 1st Edition
Languages

Table of Contents (17) Chapters

NumPy Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Winding Along with IPython Advanced Indexing and Array Concepts 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 Fun with Scikits 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...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}