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.
- Fermat's Factorization method for large numbers
- Dixon's Factorization Method with implementation
- Euler's Factorization method
- Pollard's Rho Algorithm for Prime Factorization
- Prime Factorization using Sieve O(log n) for multiple queries
- Sum of Factors of a Number using Prime Factorization
- Count occurrences of a prime number in the prime factorization of every element from the given range
- Trial division Algorithm for Prime Factorization
- Wheel Factorization Algorithm
- Transportation Problem | Set 6 (MODI Method - UV Method)
- Babylonian method for square root
- Horner's Method for Polynomial Evaluation
- Primality Test | Set 1 (Introduction and School Method)
- Program for Bisection Method
- Program for Newton Raphson Method
- Runge-Kutta 4th Order Method to Solve Differential Equation
- Fast method to calculate inverse square root of a floating point number in IEEE 754 format
- Program for Muller Method
- Program to find root of an equations using secant method
- Find n-th element in a series with only 2 digits (4 and 7) allowed | Set 2 (log(n) 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 firstname.lastname@example.org. 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