Do you know what a prime factorization is?
Example: 90 has a prime factorization of 2 * 3 * 3 * 5.
There are a few ways to go about implementing this in Lua, but first think about how you'd do it yourself.
There are two main ways to approach this.
By Hand
Let's take 1650. How do we factorize it? Well, we can pick some numbers that divide it. Pretty clearly it's divisible by 10, so
1650 = 10 * 165.
We can then split each of these into prime factors. 10 is just 2 * 5, and 165 is clearly divisible by 5, so 165 = 5 * (165/5) = 5 * 33:
1650 = 10 * 165 = (2 * 5) * (5 * 33).
Finally, 33 is just 3 * 11. We end up with all prime numbers then. So
1650 = 2 * 5 * 5 * 3 * 11.
Describe what we did more exactly:
- To get the factors of
n,
- Pick a factor of
n, call it f.
- Get the factors of
f and the factors of n / f.
- put them together.
The big question left is, how do you "pick a factor of n"?
A factor divides n cleanly, meaning there is no remainder after division. You'll probably need n % f == 0 as the condition when searching for an appropriate f. Remember to forget about f=1, since 1 is not prime!
Fundamental Theorem of Arithmetic
All integers have a unique factorization. In particular, that means that for any n,
n = 2^a * 3^b * 5^c * 7^d * ...
where 2, 3, 5, 7, ... are the primes and a b c ... are non-negative integers.
Thus you can just figure out how many times 2 goes into n, how many times 3 goes into n, etc.
This approach requires
- a list of prime numbers
- determining if
p^k divides n
Hopefully this explanation gives the information you need. There are more or less 3 ways to tackle the problem of factoring numbers -- so you should be able to pick a method that looks like it works and arrive at a solution.
1 comment
I've read this and Ayonjun told me that if I don't learn how to use % then I will have a hard time doing snackbreak problems. So I am going to step away from this and go learn how to use %.