我们有一个数字n。我们需要确定数字n是否可以由两个平方之和表示。
例子 :
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
蛮力法– O(n)
我们使用两个for循环运行直到n的平方根,然后每次检查两个循环数的平方和是否等于N.如果找到该组合,则将输出Yes,否则输出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 Program
int 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 Program
n = 25
if (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 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.
PHP
Javascript
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 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";
}
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 Code
public 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 Code
n = 169
if (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 s = new Dictionary();
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 Code
public static void Main(String[] args)
{
int n = 169;
Console.WriteLine(sumSquare(n) ?
"YES" : "NO");
}
}
// This code is contributed by Princi Singh
C++
// C++ program for Check whether a number can be
// represented by sum of two squares using binary search.
#include
#include
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
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 Code
c = 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
C++
// Check whether a number can be represented
// by sum of two squares using Fermat Theorem.
#include
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
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 Code
public 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 Code
n = 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 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
PHP
Javascript
输出:
3^2 + 4^2
Yes
我们也可以在O(sqrt(n))中解决这个问题
为了解决sqrt(n)复杂性的问题,我们使用了一个哈希表,其中将存储直到sqrt(n)的数字平方,并且每次我们在哈希表中搜索(n – sqrt(i))(如果存在),然后返回是的,其他返回否。
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 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";
}
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 Code
public 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 Code
n = 169
if (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 s = new Dictionary();
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 Code
public static void Main(String[] args)
{
int n = 169;
Console.WriteLine(sumSquare(n) ?
"YES" : "NO");
}
}
// This code is contributed by Princi Singh
输出 :
5^2 + 12^2
Yes
我们也可以在O(sqrt(n)log n)中解决这个问题
该方法由Sagar Shukla贡献。
二进制搜索方法:
另一种检查方法是一个完美的正方形,是通过使用Binary Search实现的。该方法与典型的二进制搜索来查找数字的方法相同。唯一的区别在于,我们需要找到一个介于该范围中间的整数这样这个数字就是…的平方根换句话说,我们需要在范围内找到一个整数mid ,这样midxmid =
下面是上述方法的实现:
C++
// C++ program for Check whether a number can be
// represented by sum of two squares using binary search.
#include
#include
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
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 Code
c = 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
?>
Java脚本
输出 :
true
时间复杂度:O(sqrt(c)log(c))
该方法由Sagar Shukla贡献。
费马定理方法:
该方法基于以下陈述,该陈述基于费马定理:
“当且仅当n的素数分解时,形式(4k + 3)的每个素数出现偶数次,任何正数n才能表示为两个平方的和。”
利用上述定理,我们可以直接找出给定数n是否可以表示为两个平方的和。
为此,我们只需找到给定数n的所有素数,范围可以从连同这些因素的计数,通过反复划分。如果在任何步骤中我们发现形式(4k + 3)的任何素数出现的次数都是奇数次,则可以返回False值。
如果n本身是质数,则不会被n中的任何质数整除。 。因此,我们需要检查n是否可以以(4k + 3)的形式表示。如果是这样,我们需要返回一个False值,指示此素数出现奇数(1)次。
否则,我们可以返回True值。
C++
// Check whether a number can be represented
// by sum of two squares using Fermat Theorem.
#include
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
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 Code
public 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 Code
n = 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 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
的PHP
Java脚本
输出 :
Yes