Related Articles

# Check whether a number can be represented by sum of two squares

• Difficulty Level : Medium
• Last Updated : 21 May, 2021

We have number n. We need to find whether number n can be represented by the sum of two squares.

Examples :

Input  : n = 17
Output : Yes
4^2 + 1^2 = 17

Input  : n = 169
Output : Yes
5^2 + 12^2 = 169

Input : n = 24
Output : No

Brute-force approach – O(n)
We use two for loops running till the square root of n and each time we find whether the sum of the square of both numbers of the loop is equal to N.If we find that combination, then we will print Yes, otherwise No.

for i=1 to sqrt(n)
for j=i to sqrt(n)
if (i*i+j*j == n)
return true;
return false;

## C++

 // A brute force approach based implementation// to find if a number can be written as sum// of two squares.#include using namespace std; // function to check if there exist two// numbers sum of whose squares is n.bool sumSquare(int n){    for (long i = 1; i * i <= n; i++)        for (long j = 1; j * j <= n; j++)            if (i * i + j * j == n) {                cout << i << "^2 + "                     << j << "^2" << endl;                return true;            }    return false;} // driver Programint main(){    int n = 25;    if (sumSquare(n))        cout << "Yes";    else        cout << "No";}

## Java

 // A brute force approach based implementation// to find if a number can be written as sum// of two squares. class GFG {         // function to check if there exist two    // numbers sum of whose squares is n.    static boolean sumSquare(int n)    {        for (long i = 1; i * i <= n; i++)            for (long j = 1; j * j <= n; j++)                if (i * i + j * j == n) {                    System.out.println(i + "^2 + "                                       + j + "^2");                    return true;     }         return false;    }          // driver Program    public static void main(String args[])    {        int n = 25;        if (sumSquare(n))            System.out.println("Yes");        else            System.out.println("No");    }}  /*This code is contributed by Nikita Tiwari.*/

## Python3

 # A brute force approach based# implementation to find if a number# can be written as sum of two squares. # function to check if there exist two# numbers sum of whose squares is n.def sumSquare( n) :    i = 1    while i * i <= n :        j = 1        while(j * j <= n) :            if (i * i + j * j == n) :                print(i, "^2 + ", j , "^2" )                return True            j = j + 1        i = i + 1             return False  # driver Programn = 25if (sumSquare(n)) :    print("Yes")else :    print( "No")      # This code is contributed by Nikita Tiwari.

## C#

 // A brute force approach based// implementation to find if a// number can be written as sum// of two squaresusing System; class GFG {         // function to check if there exist two    // numbers sum of whose squares is n    static bool sumSquare(int n)    {        for (long i = 1; i * i <= n; i++)            for (long j = 1; j * j <= n; j++)                if (i * i + j * j == n)                {                    Console.Write(i + "^2 + "                                    + j + "^2");                    return true;                  }        return false;    }         // Driver Code    public static void Main(String []args)    {        int n = 25;        if (sumSquare(n))            Console.Write("\nYes");        else            Console.Write("\nNo");    }} // This code is contributed by Smitha Dinesh Semwal.

## PHP

 

## Javascript

 

Output:

3^2 + 4^2
Yes

We can also have this problem in O(sqrt(n))
To solve this problem in sqrt(n) complexity, we use a hashmap where we will store the squares of numbers till sqrt(n), and each time we will search for (n – sqrt(i)) in the hashmap if it exists, then return Yes else return No.

unordered_map hashmap;
for i = 1 to sqrt(n)
hashmap[i*i]=1;
if (hashmap.find(N-i*i) != hashmap.end())
return true;
return false;


## C++

 // An efficient approach based implementation// to find if a number can be written as sum// of two squares.#include using namespace std; // function to check if there exist two// numbers sum of whose squares is n.bool sumSquare(int n){    unordered_map<int, int> s;    for (int i = 0; i * i <= n; ++i) {         // store square value in hashmap        s[i * i] = 1;        if (s.find(n - i * i) != s.end()) {            cout << sqrt(n - i * i) << "^2 + "                 << i << "^2" << endl;            return true;        }    }    return false;} // driver Programint main(){    int n = 169;    if (sumSquare(n))        cout << "Yes";    else        cout << "No";}

## Java

 // An efficient approach based implementation// to find if a number can be written as sum// of two squares.import java.util.*;class GFG{ // function to check if there exist two// numbers sum of whose squares is n.static boolean sumSquare(int n){    HashMap s = new HashMap();    for (int i = 0; i * i <= n; ++i)    {         // store square value in hashmap        s.put(i * i, 1);        if (s.containsKey(n - i * i))        {            System.out.println((int)Math.sqrt(n - i * i) +                                      "^2 + " + i + "^2");            return true;        }    }    return false;} // Driver Codepublic static void main(String[] args){    int n = 169;    System.out.print(sumSquare(n) ?                          "YES\n" : "NO\n");}} // This code is contributed by Princi Singh

## Python3

 # An efficient approach based implementation# to find if a number can be written as sum# of two squares. # function to check if there exist two# numbers sum of whose squares is n.def sumSquare(n):     s = dict()    for i in range(n):         if i * i > n:            break         # store square value in hashmap        s[i * i] = 1         if (n - i * i) in s.keys():            print((n - i * i)**(1 / 2),                       "^2 +", i, "^2")            return True             return False # Driver Coden = 169if (sumSquare(n)):    print("Yes")else:    print("No") # This code is contributed by Mohit Kumar

## C#

 // An efficient approach based implementation// to find if a number can be written as sum// of two squares.using System;using System.Collections.Generic;class GFG{ // function to check if there exist two// numbers sum of whose squares is n.static bool sumSquare(int n){    Dictionary<int, int> s = new Dictionary<int, int>();    for (int i = 0; i * i <= n; ++i)    {         // store square value in hashmap        s.Add(i * i, 1);        if (s.ContainsKey(n - i * i))        {            Console.WriteLine((int)Math.Sqrt(n - i * i) +                                     "^2 + " + i + "^2");            return true;        }    }    return false;} // Driver Codepublic static void Main(String[] args){    int n = 169;    Console.WriteLine(sumSquare(n) ?                             "YES" : "NO");}} // This code is contributed by Princi Singh

## Javascript

 

Output :

5^2 + 12^2
Yes

We can also this problem in O(sqrt(n)log n)
This approach has been contributed by Sagar Shukla.

Binary Search Approach :
Another method to check if is a perfect square is by making use of binary search. The method remains the same as that of a typical binary search to find a number. The only difference lies in that we need to find an integer, mid in the range such that this number is the square root of Or in other words, we need to find an integer, mid, in the range , such that midxmid Below is the implementation of the above approach:

## C++

 // C++ program for Check whether a number can be// represented by sum of two squares using binary search.#include#includeusing namespace std; // Function for binary search.bool binary_search(int num2, int se, int num){    int mid;    int ss=0;     while(ss<=se)    {        // Calculating mid.        mid=(ss+se)/2;        if ((pow(mid,2)+pow(num2,2))==num)        {            return true;        }        else if ((pow(mid,2)+pow(num2,2))>num)        {            se=mid-1;        }        else        {            ss=mid+1;        }    }    return false;} // Driver codeint main(){    int rt;    int num=169;    rt=sqrt(num);    bool flag=false;    for (int i = rt; i >=0; --i)    {        if (binary_search(i,i,num))        {            flag=true;            break;        }    }    if (flag)    {        cout<<"true";    }    else cout<<"false";    return 0;}// This code is contributed by Dhruv Gupta

## Java

 // Java program for Check whether a number can be// represented by sum of two squares using binary search.import java.util.*;import java.lang.*; public class GfG {    public static boolean judgeSquareSum(int c)    {         // Iterating loop from 0 to c - a * a.        for (long a = 0; a * a <= c; a++) {            int b = c - (int)(a * a);             // If b is a square root of c - a * a            // then return true.            if (binary_search(0, b, b))                return true;        }        return false;    }     // Function for binary search.    public static boolean binary_search(long s, long e, int n)    {         // If lower limit exceeds upper limit.        if (s > e)            return false;         // Calculating mid.        long mid = s + (e - s) / 2;        if (mid * mid == n)            return true;        if (mid * mid > n)            return binary_search(s, mid - 1, n);        return binary_search(mid + 1, e, n);    }     // Driver function    public static void main(String argc[])    {        int c = 17;        System.out.println(judgeSquareSum(c));    }}

## Python3

 # Python3 program for Check whether # a number can be represented by# sum of two squares using binary search.   def judgeSquareSum(c):       # Iterating loop from 0 to c - a * a.    a = 0;    while(a * a <= c):        b = c - int(a * a);           # If b is a square root of         # c - a * a then return true.        if (binary_search(0, b, b)):            return 1;        a+=1;    return 0;   # Function for binary search.def binary_search(s, e, n):    # If lower limit exceeds     # upper limit.    if (s > e):        return 0;         # Calculating mid.    mid = s + int((e - s) / 2);    if (int(mid * mid) == n):        return 1;         if (int(mid * mid) > n):        return binary_search(s, mid - 1, n);         return binary_search(mid + 1, e, n);   # Driver Codec = 17;if(judgeSquareSum(c)):    print("true");else:    print("false");   # This code is contributed by mits

## C#

 // C# program for Check whether a// number can be represented by// sum of two squares using// binary search.using System;class GFG { public static bool judgeSquareSum(int c)    {        // Iterating loop from 0 to c - a * a.        for (long a = 0; a * a <= c; a++)        {            int b = c - (int)(a * a);             // If b is a square root of c - a * a            // then return true.            if (binary_search(0, b, b))                return true;        }        return false;    }     // Function for binary search.    public static bool binary_search(long s,                              long e, int n)    {         // If lower limit exceeds upper limit.        if (s > e)            return false;         // Calculating mid.        long mid = s + (e - s) / 2;                 if (mid * mid == n)            return true;                     if (mid * mid > n)            return binary_search(s, mid - 1, n);                     return binary_search(mid + 1, e, n);    }         // Driver Code    public static void Main()    {        int c = 17;        Console.WriteLine(judgeSquareSum(c));    }} // This code is contributed by Sam007

## PHP

  $e) return 0;  // Calculating mid. $mid = $s + intval(($e - $s) / 2); if (intval($mid * $mid) == $n)            return 1;                     if (intval($mid * $mid) > $n) return binary_search($s, $mid - 1, $n);                     return binary_search($mid + 1, $e, $n); } // Driver Code$c = 17;if(judgeSquareSum(\$c))    echo "true";else    echo "false"; // This code is contributed by Sam007?>

## Javascript

 

Output:

true

Time complexity : O(sqrt(c)log(c))
This approach has been contributed by Sagar Shukla.

### Fermat Theorem Approach:

This approach is based on the following statement, which is based on Fermat’s Theorem:
“Any positive number n is expressible as a sum of two squares if and only if the prime factorization of n, every prime of the form (4k + 3) occurs an even number of times.”
By making use of the above theorem, we can directly find out if the given number n can be expressed as a sum of two squares.
To do so, we simply find all the prime factors of the given number n, which could range from along with the count of those factors, by repeated division. If at any step, we find out that the number of occurrences of any prime factor of the form (4k + 3)occurs an odd number of times, we can return a false value.
If n itself is a prime number, it won’t be divisible by any of the primes in . Thus, we need to check if n can be expressed in the form of (4k + 3). If so, we need to return a false value, indicating that this prime occurs an odd number(1) of times.
Otherwise, we can return the true value.

## C++

 // Check whether a number can be represented// by sum of two squares using Fermat Theorem.#includeusing namespace std; bool judgeSquareSum(int n){for (int i = 2;        i * i <= n; i++){    int count = 0;    if (n % i == 0)    {        // Count all the prime factors.        while (n % i == 0)        {            count++;            n /= i;        }         // Ifany prime factor of the form        // (4k+3)(4k+3) occurs an odd        // number of times.        if (i % 4 == 3 && count % 2 != 0)            return false;    }} // If n itself is a x prime number and// can be expressed in the form of// 4k + 3 we return false.return n % 4 != 3;} // Driver Codeint main(){    int n = 17;    if(judgeSquareSum(n))        cout << "Yes";    else        cout << "No";}         // This code is contributed by// prabhat kumar singh

## Java

 // Java program to Check whether a number // can be represented by sum of two// squares using Fermat Theorem.import java.util.*;import java.lang.*; class GFG{public static boolean judgeSquareSum(int n){    for (int i = 2; i * i <= n; i++)    {        int count = 0;        if (n % i == 0)        {            // Count all the prime factors.            while (n % i == 0)            {                count++;                n /= i;            }                         // Ifany prime factor of the form            // (4k+3)(4k+3) occurs an odd            // number of times.            if (i % 4 == 3 && count % 2 != 0)                return false;        }    }         // If n itself is a prime number and can    // be expressed in the form of 4k + 3    // we return false.    return n % 4 != 3;} // Driver Codepublic static void main(String argc[]){    int n = 17;    if(judgeSquareSum(n))        System.out.println("Yes");    else        System.out.println("No");}}

## Python3

 # Check whether a number can be represented# by sum of two squares using Fermat Theorem.def judgeSquareSum(n):     i = 2;    while (i * i <= n):        count = 0;        if (n % i == 0):                         # Count all the prime factors.            while (n % i == 0):                count += 1;                n = int(n / i);                 # Ifany prime factor of the            # form (4k+3)(4k+3) occurs            # an odd number of times.            if (i % 4 == 3 and count % 2 != 0):                return False;        i += 1;         # If n itself is a x prime number and    # can be expressed in the form of 4k + 3    # we return false.    return n % 4 != 3; # Driver Coden = 17;if(judgeSquareSum(n)):    print("Yes");else:    print("No");     # This code is contributed by mits

## C#

 // C# program to Check whether a number// can be represented by sum of two// squares using Fermat Theorem.using System; class GFG{public static bool judgeSquareSum(int n){    for (int i = 2; i * i <= n; i++)    {        int count = 0;        if (n % i == 0)        {            // Count all the prime factors.            while (n % i == 0)            {                count++;                n /= i;            }                         // If any prime factor of the            // form (4k+3)(4k+3) occurs an            // odd number of times.            if (i % 4 == 3 && count % 2 != 0)                return false;        }    }         // If n itself is a prime number and    // can be expressed in the form of    // 4k + 3 we return false.    return n % 4 != 3;} // Driver Codestatic public void Main (){    int n = 17;    if(judgeSquareSum(n))        Console.WriteLine("Yes");    else        Console.WriteLine("No");}} // This code is contributed// by akt_mit

## PHP

 

## Javascript

 

Output :

Yes

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up