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

We have a 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 loop running till squareroot of n and each time we will check whether the sum of square of both numbers of loop is equal to N.If we found 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// A brute force approach based implementation
// to find if a number can be written as sum
// of two squares.
#include <bits/stdc++.h>
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 Program
int main()
{
    int n = 25;
    if (sumSquare(n))
        cout << "Yes";
    else
        cout << "No";
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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.*/

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 Program
n = 25
if (sumSquare(n)) :
    print("Yes")
else :
    print( "No")
      
  
# This code is contributed by Nikita Tiwari.

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// A brute force approach based 
// implementation to find if a 
// number can be written as sum
// of two squares 
using 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.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// 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.
function sumSquare(int $n)
{
    for ($i = 1; $i * $i <= $n; $i++)
        for ( $j = 1; $j * $j <= $n; $j++)
            if ($i * $i + $j * $j ==$n
            {
                echo $i , "^2 + ",
                    $j , "^2" ;
                return true;
            }
    return false;
}
      
    // Driver Code
    $n = 25;
    if (sumSquare($n))
        echo " \n","Yes";
    else
        echo "No";
  
// This code is contributed by anuj_67.
?>

chevron_right



Output:

3^2 + 4^2
Yes

We can also this problem in O(sqrt(n))
For solving this problem in sqrt(n) complexity we use a hashmap where we will store the squares of number 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// An efficient approach based implementation
// to find if a number can be written as sum
// of two squares.
#include <bits/stdc++.h>
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 Program
int main()
{
    int n = 169;
    if (sumSquare(n))
        cout << "Yes";
    else
        cout << "No";
}

chevron_right


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 Code
n = 169
if (sumSquare(n)):
print(“Yes”)
else:
print(“No”)

# This code is contributed by Mohit Kumar


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  c - a^2 is a perfect square, is by making use of Binary Search. The method remains 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 [0, c - a^2] such that this number is the square root of  c - a^2 Or in other words, we need to find an integer, mid, in the range [0, c - a^2], such that midxmid = c - a^2

Below is the implementation of above approach :

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for Check whether a number can be
// represented by sum of two squares using binary search.
#include<iostream>
#include<cmath>
using 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 code
int 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

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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));
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 Code 
c = 17
if(judgeSquareSum(c)): 
    print("true"); 
else:
    print("false"); 
    
# This code is contributed by mits

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program for Check whether 
// a number can be represented by
// sum of two squares using binary search.
  
function judgeSquareSum($c)
    {
  
        // Iterating loop from 0 to c - a * a.
        for ($a = 0; $a * $a <= $c; $a++) 
        {
            $b = $c - intval($a * $a);
  
            // If b is a square root of 
            // c - a * a then return true.
            if (binary_search(0, $b, $b))
                return 1;
        }
        return 0;
    }
  
    // Function for binary search.
    function binary_search($s, $e, $n)
    {
  
        // If lower limit exceeds 
        // upper limit.
        if ($s > $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
?>

chevron_right



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 [2,\sqrt{n}] along with the count of those factors, by repeated division. If at any step, we find out that the number of occurrence of any prime factor of the form (4k + 3)occurs an odd number of times, we can return a False value.

In case, n itself is a prime number, it won’t be divisible by any of the primes in the [2,\sqrt{n}]. 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 a True value.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// Check whether a number can be represented 
// by sum of two squares using Fermat Theorem.
#include<bits/stdc++.h>
using 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 Code
int main()
{
    int n = 17;
    if(judgeSquareSum(n))
        cout << "Yes";
    else
        cout << "No";
}
          
// This code is contributed by 
// prabhat kumar singh

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 Code
public static void main(String argc[])
{
    int n = 17;
    if(judgeSquareSum(n))
        System.out.println("Yes");
    else
        System.out.println("No");
}
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 Code 
n = 17
if(judgeSquareSum(n)): 
    print("Yes"); 
else:
    print("No"); 
      
# This code is contributed by mits

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 Code 
static public void Main ()
{
    int n = 17;
    if(judgeSquareSum(n))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
}
}
  
// This code is contributed 
// by akt_mit

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// Check whether a number can be represented 
// by sum of two squares using Fermat Theorem. 
function judgeSquareSum($n
    for ($i = 2; $i * $i <= $n; $i++) 
    
        $count = 0; 
        if ($n % $i == 0) 
        
            // Count all the 
            // prime factors. 
            while ($n % $i == 0) 
            
                $count++; 
                $n = (int) $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 Code 
$n = 17; 
if(judgeSquareSum($n)) 
    echo "Yes"
else
    echo "No"
      
// This code is contributed by ajit 
?>

chevron_right



Output :

Yes


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.