Fermat’s Factorization method is based on the representation of an odd integer as the difference of two squares.
For an integer n, we want a and b such as:
n = a2 - b2 = (a+b)(a-b) where (a+b) and (a-b) are the factors of the number n
Input: n = 6557 Output: [79,83] Explanation: For the above value, the first try for a is ceil value of square root of 6557, which is 81. Then, b2 = 812 - 6557 = 4, as it is a perfect square. So, b = 2 So, the factors of 6557 are: (a - b) = 81 -2 = 79 & (a + b) = 81 + 2 = 83.
- If n = pq is a factorization of n into two positive integers, Then, since n is odd, so p and q are both odd.
- Let, a = 1/2 * (p+q) and b = 1/2 * (q-p).
- Since a and b are both integers, then p = (a – b) and q = (a + b).
- So, n = pq = (a – b)(a + b) = a2 – b2
- In case of prime number, we go back until b = 1 in as one factor is 1 for a prime number.
- A while loop ensures this operation
Below is the implementation of the above approach
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.
- Euler's Factorization method
- Dixon's Factorization Method with implementation
- Fermat's Factorization method for large numbers
- Wheel Factorization Algorithm
- Pollard's Rho Algorithm for Prime Factorization
- Sum of Factors of a Number using Prime Factorization
- Prime Factorization using Sieve O(log n) for multiple queries
- Trial division Algorithm for Prime Factorization
- Count occurrences of a prime number in the prime factorization of every element from the given range
- Transportation Problem | Set 6 (MODI Method - UV Method)
- Program for Bisection Method
- Program for Muller Method
- Math floorDiv() method in Java
- Java Math incrementExact(int x) method
- Babylonian method for square root
- Primality Test | Set 2 (Fermat Method)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : AnkitRai01