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++
#include <bits/stdc++.h>
using namespace std;
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 ;
}
int main()
{
int n = 25;
if (sumSquare(n))
cout << "Yes" ;
else
cout << "No" ;
}
|
Java
class GFG {
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 ;
}
public static void main(String args[])
{
int n = 25 ;
if (sumSquare(n))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
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
n = 25
if (sumSquare(n)) :
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG {
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 ;
}
public static void Main(String []args)
{
int n = 25;
if (sumSquare(n))
Console.Write( "\nYes" );
else
Console.Write( "\nNo" );
}
}
|
PHP
<?php
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;
}
$n = 25;
if (sumSquare( $n ))
echo " \n" , "Yes" ;
else
echo "No" ;
?>
|
Javascript
<script>
function sumSquare(n) {
for (i = 1; i * i <= n; i++)
for (j = 1; j * j <= n; j++)
if (i * i + j * j == n) {
document.write(i + "^2 + " + j + "^2" + "<br/>" );
return true ;
}
return false ;
}
var n = 25;
if (sumSquare(n))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
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++
#include <bits/stdc++.h>
using namespace std;
bool sumSquare( int n)
{
unordered_map< int , int > s;
for ( int i = 0; i * i <= n; ++i) {
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 ;
}
int main()
{
int n = 169;
if (sumSquare(n))
cout << "Yes" ;
else
cout << "No" ;
}
|
Java
import java.util.*;
class GFG
{
static boolean sumSquare( int n)
{
HashMap<Integer,
Integer> s = new HashMap<Integer,
Integer>();
for ( int i = 0 ; i * i <= n; ++i)
{
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 ;
}
public static void main(String[] args)
{
int n = 169 ;
System.out.print(sumSquare(n) ?
"YES\n" : "NO\n" );
}
}
|
Python3
def sumSquare(n):
s = dict ()
for i in range (n):
if i * i > n:
break
s[i * i] = 1
if (n - i * i) in s.keys():
print ((n - i * i) * * ( 1 / 2 ),
"^2 +" , i, "^2" )
return True
return False
n = 1
if n = = 1 :
print ( '0^2 + 1^2' )
elif (sumSquare(n)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static bool sumSquare( int n)
{
Dictionary< int , int > s = new Dictionary< int , int >();
for ( int i = 0; i * i <= n; ++i)
{
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 ;
}
public static void Main(String[] args)
{
int n = 169;
Console.WriteLine(sumSquare(n) ?
"YES" : "NO" );
}
}
|
Javascript
<script>
function sumSquare(n)
{
let s = new Map();
for (let i = 0; i * i <= n; ++i){
s.set(i * i, 1);
if (s.has(n - i * i))
{
document.write(Math.sqrt(n - i * i) +
"^2 + " + i + "^2<br>" );
return true ;
}
}
return false ;
}
let n = 169;
document.write(sumSquare(n) ?
"YES<br>" : "NO<br>" );
</script>
|
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++
#include<iostream>
#include<cmath>
using namespace std;
bool binary_search( int num2, int se, int num)
{
int mid;
int ss=0;
while (ss<=se)
{
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 ;
}
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;
}
|
Java
import java.util.*;
import java.lang.*;
public class GfG {
public static boolean judgeSquareSum( int c)
{
for ( long a = 0 ; a * a <= c; a++) {
int b = c - ( int )(a * a);
if (binary_search( 0 , b, b))
return true ;
}
return false ;
}
public static boolean binary_search( long s, long e, int n)
{
if (s > e)
return false ;
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);
}
public static void main(String argc[])
{
int c = 17 ;
System.out.println(judgeSquareSum(c));
}
}
|
Python3
def judgeSquareSum(c):
a = 0 ;
while (a * a < = c):
b = c - int (a * a);
if (binary_search( 0 , b, b)):
return 1 ;
a + = 1 ;
return 0 ;
def binary_search(s, e, n):
if (s > e):
return 0 ;
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);
c = 17 ;
if (judgeSquareSum(c)):
print ( "true" );
else :
print ( "false" );
|
C#
using System;
class GFG {
public static bool judgeSquareSum( int c)
{
for ( long a = 0; a * a <= c; a++)
{
int b = c - ( int )(a * a);
if (binary_search(0, b, b))
return true ;
}
return false ;
}
public static bool binary_search( long s,
long e, int n)
{
if (s > e)
return false ;
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);
}
public static void Main()
{
int c = 17;
Console.WriteLine(judgeSquareSum(c));
}
}
|
PHP
<?php
function judgeSquareSum( $c )
{
for ( $a = 0; $a * $a <= $c ; $a ++)
{
$b = $c - intval ( $a * $a );
if (binary_search(0, $b , $b ))
return 1;
}
return 0;
}
function binary_search( $s , $e , $n )
{
if ( $s > $e )
return 0;
$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 );
}
$c = 17;
if (judgeSquareSum( $c ))
echo "true" ;
else
echo "false" ;
?>
|
Javascript
<script>
function judgeSquareSum(c) {
for (a = 0; a * a <= c; a++) {
var b = c - parseInt( (a * a));
if (binary_search(0, b, b))
return true ;
}
return false ;
}
function binary_search(s , e , n) {
if (s > e)
return false ;
var mid = s + parseInt((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);
}
var c = 17;
document.write(judgeSquareSum(c));
</script>
|
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++
#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)
{
while (n % i == 0)
{
count++;
n /= i;
}
if (i % 4 == 3 && count % 2 != 0)
return false ;
}
}
return n % 4 != 3;
}
int main()
{
int n = 17;
if (judgeSquareSum(n))
cout << "Yes" ;
else
cout << "No" ;
}
|
Java
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 )
{
while (n % i == 0 )
{
count++;
n /= i;
}
if (i % 4 == 3 && count % 2 != 0 )
return false ;
}
}
return n % 4 != 3 ;
}
public static void main(String argc[])
{
int n = 17 ;
if (judgeSquareSum(n))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def judgeSquareSum(n):
i = 2 ;
while (i * i < = n):
count = 0 ;
if (n % i = = 0 ):
while (n % i = = 0 ):
count + = 1 ;
n = int (n / i);
if (i % 4 = = 3 and count % 2 ! = 0 ):
return False ;
i + = 1 ;
return n % 4 ! = 3 ;
n = 17 ;
if (judgeSquareSum(n)):
print ( "Yes" );
else :
print ( "No" );
|
C#
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)
{
while (n % i == 0)
{
count++;
n /= i;
}
if (i % 4 == 3 && count % 2 != 0)
return false ;
}
}
return n % 4 != 3;
}
static public void Main ()
{
int n = 17;
if (judgeSquareSum(n))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
PHP
<?php
function judgeSquareSum( $n )
{
for ( $i = 2; $i * $i <= $n ; $i ++)
{
$count = 0;
if ( $n % $i == 0)
{
while ( $n % $i == 0)
{
$count ++;
$n = (int) $n / $i ;
}
if ( $i % 4 == 3 &&
$count % 2 != 0)
return false;
}
}
return $n % 4 != 3;
}
$n = 17;
if (judgeSquareSum( $n ))
echo "Yes" ;
else
echo "No" ;
?>
|
Javascript
<script>
function judgeSquareSum(n)
{
for (i = 2; i * i <= n; i++)
{
var count = 0;
if (n % i == 0)
{
while (n % i == 0)
{
count++;
n = parseInt(n / i);
}
if (i % 4 == 3 && count % 2 != 0)
return false ;
}
}
return n % 4 != 3;
}
var n = 17;
if (judgeSquareSum(n))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Output :
Yes
Time complexity: O(?(n))
Auxiliary space: O(1)