Let’s see how we can split a real number into prime numbers.
One of the main theorems in mathematics states that every real number R (R > 1) can be represented with prime numbers P1, P2, P3 where (P1 < P2 < P3.. etc.)
So for example:
- 520 = 2 * 2 * 2 * 5 * 13
- 64 = 2 * 2 * 2 * 2 * 2 * 2
- 2345 = 5 * 7 * 67
How we can do that in C:
1. Include the library needed for in/output to the console.
#include stdio.h
2. Next we declare the number which we want to factorize
unsigned n = 432;
3. We should have a variable that is the current factor. We start from 1, but in the beginning of the “while” we increment, so effectively we are starting from 2.
unsigned i = 1;
4. We declare the body of the main (outer) loop. It will process until the number we are factorizing is different from 1.
while (n != 1) {
....
}
5. First step in the loop is to increment “i” which will lead us to the next factor.
Note: this code is in the main “while” loop described above.
i++;
6. We need a variable to count the number of times the current factor is contained in “n”.
unsigned k = 0;
7. We start another (inner) “while” loop that will divide “n” by “i” until it cannot be evenly divided.
while (n % i == 0) {
....
}
8. In the above (inner) “while” loop we increment “k” (the number of times a factor exists in the number we want to factorize – “n”). And we also reduce “n”, by dividing it with “i”.
k++;
n /= i;
9. Next we print the current factor “i”, “k” number of times.
for (j = 0; j < k; j++) {
printf("%u ", i);
}
That’s it! As console output we get all the factors, starting from the smallest.
Hope you enjoyed this lesson, if you did, please subscribe for more!
