1
A better algorithm for factoring odd positive integers is Fermat's factorization algorithm.
Let $n= ab$ be an odd composite number. Prove that $n$ can be written as the difference of two perfect squares:
\n\\begin{equation*}\nn = x^2 - y^2 = (x - y)(x + y).\n\\end{equation*}\nConsequently, a positive odd integer can be factored exactly when we can find integers $x$ and $y$ such that $n = x^2 - y^2\\text{.}$
Write a program to implement the following factorization algorithm based on the observation in part (a). The expression
ceiling(sqrt(n))
means the smallest integer greater than or equal to the square root of $n\\text{.}$ Write another program to do factorization using trial division and compare the speed of the two algorithms. Which algorithm is faster and why?
x := ceiling(sqrt(n))\ny := 1\n\n1 : while x^2 - y^2 > n do\n y := y + 1\n\nif x^2 - y^2 < n then\n x := x + 1\n y := 1\n goto 1\nelse if x^2 - y^2 = 0 then\n a := x - y\n b := x + y\n write n = a * b\n