Given a number N, the task is to check if this number can be represented as the difference of two perfect squares or not.
Input: N = 3
22 – 11 = 3
Input: N = 10
Approach: The idea is that all the numbers can be represented as the difference of two squares except the numbers which yield the remainder of 2 when divided by 4.
Let’s visualize this by taking a few examples:
N = 4 => 42 - 02 N = 6 => Can't be expressed as 6 % 4 = 2 N = 8 => 32 - 12 N = 10 => Can't be expressed as 10 % 4 = 2 N = 11 => 62 - 52 N = 12 => 42 - 22 and so on...
Therefore, the idea is to simply check the remainder for 2 when the given number is divided by 4.
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer Geeks Classes Live