Trial Division
October 25, 2016
It was a gorgeous autumn weekend: brisk mornings, warm sunny afternoons, and absolutely no reason to sit at a computer screen indoors. And even though the programming on my big project at work is finished, there are still details to be looked after, so I had no time there, either. Thus, another recycled exercise today, another one that I’ve seen on the beginning-programmer message boards recently:
Write a program that determines the prime factors of a number n.
You should write at the level of a first-year programmer, nothing sophisticated. An appropriate algorithm is trial division.
Your task is to write a program to factor integers. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Very basic Python 3 solution that divides out by 2 and then by each odd number until the reduced n becomes less than the square of the factor to be tested.
I used Python’s builtin divmod instead of separate modulo and division.
Here’s another Python solution, to make things more interesting, it factorizes Gaussian integers (ie. integral complex numbers):