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:
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.
- Print numbers such that no two consecutive numbers are co-prime and every three consecutive numbers are co-prime
- Find all Factors of Large Perfect Square Natural Number in O(sqrt(sqrt(N))
- Check if a number is Prime, Semi-Prime or Composite for very large numbers
- Dividing a Large file into Separate Modules in C/C++, Java and Python
- Find N % 4 (Remainder with 4) for a large value of N
- Uniform-Cost Search (Dijkstra for large Graphs)
- Comparing X^Y and Y^X for very large values of X and Y
- Knapsack with large Weights
- Number of factors of very large number N modulo M where M is any prime number
- Check if a binary string has two consecutive occurrences of one everywhere
- Find last two remaining elements after removing median of any 3 consecutive elements repeatedly
- Count the number of ordered sets not containing consecutive numbers
- Find pairs of elements from two different arrays whose product is a perfect square
- Minimum area of square holding two identical rectangles
- Find all numbers between range L to R such that sum of digit and sum of square of digit is prime
- Sum of minimum difference between consecutive elements of an array
- Numbers less than N which are product of exactly two distinct prime numbers
- Rearrange numbers in an array such that no two adjacent numbers are same
- Count subarrays with sum as difference of squares of two numbers
- Absolute Difference between the Sum of Non-Prime numbers and Prime numbers of an Array
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.