Square Difference of Two large Consecutive Numbers
Given two positive consecutive numbers M and N, the task is to find the square difference of the two numbers without computing the square of those numbers.
Input: N = 4, M = 5
52 – 42 = 25 – 16 = 9.
Input: N = 999999999, M = 1000000000
Approach: The idea is to use the algebraic expression to solve this problem. It is given in the question that M = N + 1. Therefore:
- The value to be computed is M2 – N2.
- On replacing M with N + 1, the above equation becomes:
(N + 1)2 - N2
- (N + 1)2 can be expanded to:
N2 + 12 + 2 * N - N2
- On simplifying, the above equation becomes:
1 + 2 * N 1 + N + N (1 + N) + N M + N
- Therefore, we simply need to compute and return the value of M + N.
Below is the implementation of the above approach: