Check whether a number can be represented as difference of two squares

Given a number N, the task is to check if this number can be represented as the difference of two perfect squares or not.

Examples:

Input: N = 3
Output: Yes
Explanation:
22 – 11 = 3



Input: N = 10
Output: No

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to check whether a number
// can be represented by the difference
// of two squares
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to check whether a number
// can be represented by the difference
// of two squares
bool difSquare(int n)
{
    // Checking if n % 4 = 2 or not
    if (n % 4 != 2) {
        return true;
    }
  
    return false;
}
  
// Driver code
int main()
{
  
    int n = 45;
    if (difSquare(n)) {
        cout << "Yes\n";
    }
    else {
        cout << "No\n";
    }
    return 0;
}

chevron_right


Output:

Yes

GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details

My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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.