Factorizing a large odd integer, n, into its corresponding prime factors can prove to be a difficult task. A brute approach can be testing all integers less than n until a divisor is found. This proves to be very time consuming as a divisor might be a very large prime itself.
Pollard p-1 algorithm is a better approach to find out prime factors of any integer. Using the combined help of Modular Exponentiation and GCD, it is able to calculate all the distinct prime factors in no time.
- Given a number n.
Initialize a = 2, i = 2
- Until a factor is returned do
a <- (a^i) mod n
d <- GCD(a-1, n)
if 1 < d < n then
i <- i+1
- Other factor, d' <- n/d
- If d' is not prime
n <- d'
d and d' are two prime factors.
In the above algorithm, the power of ‘a’ is continuously raised until a factor, ‘d’, of n is obtained. Once d is obtained, another factor, ‘d”, is n/d. If d’ is not prime, the same task is repeated for d’
Input : 1403 Output : Prime factors of 1403 are 61 23. Explanation : n = 1403, a = 2, i = 2 1st Iteration: a = (2^2) mod 1403 = 4 d = GCD(3, 1403) = 1 i = 2 + 1 = 3 2nd Iteration: a = (4^3) mod 1403 = 64 d = GCD(63, 1403) = 1 i = 3 + 1 = 4 3rd Iteration: a = (64^4) mod 1403 = 142 d = GCD(141, 1403) = 1 i = 4 + 1 = 5 4th Iteration: a = (142^5) mod 1403 = 794 d = GCD(793, 1403) = 61 Since 1 < d < n, one factor is 61. d' = 1403 / 61 = 23. Input : 2993 Output : Prime factors of 2993 are 41 73.
Below is the implementation.
Prime factors of 1403 are 61 23
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer Geeks Classes Live