Have you ever had a math problem that required you to try hundreds or even thousands of combinations? Have you ever wondered if there is a better way? In this tutorial, you will learn how to do this using python. If you are already imagining how you should do it, I encourage you to try it yourself first but if not, don’t worry, I show you everything you need to know to make it here.
In this first part, we will learn how to find the factors of a number and in the second, we will generalize this. If you just want the code, you can find it at the bottom but I encourage you to read this and learn the code actually works.
I’m now going to introduce you to a concept called pseudo-code. Pseudo-code is when you write code in layman’s terms. In other words, we will write code in plain English. This is especially useful if you want the readers to be able to translate your code into other programming languages. Some of the people who read your code may be able to code python but others may use java or c#.
The first thing we must do is initialize our variables.
Set num = what you want the number to be
We will define a function:
Which take one input, a number we will call:
Inside of GetFactors, we will:
Set factors = [1, X]
since all numbers have a factor 1 and itself.
In this step we must loop through 2 until X and find the factors of the number. We can do:
for i in range(2, int(X / 2) + 1):
If you don’t understand the /, check out this lesson. The int function rounds the number inside it down. The X / 2 uses a trick that all of a number’s factors (besides one and itself) are in between 2 and half of that number.
Now we need to check if each number is a factor of X. Under the for loop, we do the following:
if X / i = int(X / i), add i to the list of factors
If (and only if) i is a factor of X, X/i will be equal to X/i rounded to the nearest integer. If this is true, the number can be safely added to the list of factors. After all this is done, we can:
Try it yourself
I encourage you to try and implement this code yourself. Below is what it should look like:
You’ve now made an algorithm to find factors. Never do this by hand again! In the next tutorial, we will be making another trial and error algorithm for a more general problem. See you then!