Minimum number of squares whose sum equals to a given number N | Set-3

A number can always be represented as a sum of squares of other numbers. Note that 1 is a square, and we can always break a number as (1*1 + 1*1 + 1*1 + …). Given a number n, find the minimum number of squares that sum to N.
Examples:
Input: N = 13Â
Output: 2Â
Explanation:Â
13 can be expressed as, 13 = 32 + 22. Hence, the output is 2.Input: N = 100Â
Output: 1Â
Explanation:Â
100 can be expressed as 100 = 102. Hence, the output is 1.
Naive Approach: For [O(N*sqrt(N))] approach, please refer to Set 2 of this article.
Efficient Approach: To optimize the naive approach the idea is to use Lagrange’s Four-Square Theorem and Legendre’s Three-Square Theorem. The two theorems are discussed below:Â
Lagrange’s four-square theorem, also known as Bachet’s conjecture, states that every natural number can be represented as the sum of four integer squares, where each integer is non-negative.Â
Legendre’s three-square theorem states that a natural number can be represented as the sum of three squares of integers if and only if n is not of the form : n = 4a (8b+7), for non-negative integers a and b.Â
Therefore, it is proved that the minimum number of squares to represent any number N can only be within the set {1, 2, 3, 4}. Thus, only checking for these 4 possible values, the minimum number of squares to represent any number N can be found. Follow the steps below:
- If N is a perfect square, then the result is 1.
- If N can be expressed as the sum of two squares, then the result is 2.
- If N cannot be expressed in the form of N = 4a (8b+7), where a and b are non-negative integers, then the result is 3 by Legendre’s three-square theorem.Â
- If all the above conditions are not satisfied, then by Lagrange’s four-square theorem, the result is 4.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;Â
// Function that returns true if N// is a perfect squarebool isPerfectSquare(int N){Â Â Â Â int floorSqrt = sqrt(N);Â
    return (N == floorSqrt * floorSqrt);}Â
// Function that returns true check if// N is sum of three squaresbool legendreFunction(int N){Â Â Â Â // Factor out the powers of 4Â Â Â Â while (N % 4 == 0)Â Â Â Â Â Â Â Â N /= 4;Â
    // N is NOT of the    // form 4^a * (8b + 7)    if (N % 8 != 7)        return true;    else        return false;}Â
// Function that finds the minimum// number of square whose sum is Nint minSquares(int N){Â
    // If N is perfect square    if (isPerfectSquare(N))        return 1;Â
    // If N is sum of 2 perfect squares    for (int i = 1; i * i < N; i++) {        if (isPerfectSquare(N - i * i))            return 2;    }Â
    // If N is sum of 3 perfect squares    if (legendreFunction(N))        return 3;Â
    // Otherwise, N is the    // sum of 4 perfect squares    return 4;}Â
// Driver codeint main(){    // Given number    int N = 123;Â
    // Function call    cout << minSquares(N);    return 0;} |
Java
// Java program for the above approachimport java.util.*;Â
class GFG{Â
// Function that returns true if N// is a perfect squarestatic boolean isPerfectSquare(int N){Â Â Â Â int floorSqrt = (int)Math.sqrt(N);Â
    return (N == floorSqrt * floorSqrt);}Â
// Function that returns true check if// N is sum of three squaresstatic boolean legendreFunction(int N){Â Â Â Â Â Â Â Â Â // Factor out the powers of 4Â Â Â Â while (N % 4 == 0)Â Â Â Â Â Â Â Â N /= 4;Â
    // N is NOT of the    // form 4^a * (8b + 7)    if (N % 8 != 7)        return true;    else        return false;}Â
// Function that finds the minimum// number of square whose sum is Nstatic int minSquares(int N){Â
    // If N is perfect square    if (isPerfectSquare(N))        return 1;Â
    // If N is sum of 2 perfect squares    for(int i = 1; i * i < N; i++)     {        if (isPerfectSquare(N - i * i))            return 2;    }Â
    // If N is sum of 3 perfect squares    if (legendreFunction(N))        return 3;Â
    // Otherwise, N is the    // sum of 4 perfect squares    return 4;}Â
// Driver codepublic static void main(String[] args){         // Given number    int N = 123;Â
    // Function call    System.out.print(minSquares(N));}}Â
// This code is contributed by 29AjayKumar |
Python3
# Python3 program for the above approachfrom math import sqrt, floor, ceilÂ
# Function that returns True if N# is a perfect squaredef isPerfectSquare(N):Â Â Â Â Â Â Â floorSqrt = floor(sqrt(N))Â Â Â Â return (N == floorSqrt * floorSqrt)Â Â Â # Function that returns True check if# N is sum of three squaresdef legendreFunction(N):Â Â Â Â Â Â Â # Factor out the powers of 4Â Â Â Â while (N % 4 == 0):Â Â Â Â Â Â Â Â N //= 4Â
    # N is NOT of the    # form 4^a * (8b + 7)    if (N % 8 != 7):        return True    else:        return FalseÂ
# Function that finds the minimum# number of square whose sum is Ndef minSquares(N):       # If N is perfect square    if (isPerfectSquare(N)):        return 1Â
    # If N is sum of 2 perfect squares    for i in range(N):        if i * i < N:            break        if (isPerfectSquare(N - i * i)):            return 2               # If N is sum of 3 perfect squares    if (legendreFunction(N)):        return 3           # Otherwise, N is the    # sum of 4 perfect squares    return 4   # Driver codeif __name__ == '__main__':Â
    # Given number    N = 123Â
    # Function call    print(minSquares(N))Â
# This code is contributed by mohit kumar 29 |
C#
// C# program for the above approachusing System;Â
class GFG{Â
// Function that returns true if N// is a perfect squarestatic bool isPerfectSquare(int N){Â Â Â Â int floorSqrt = (int)Math.Sqrt(N);Â
    return (N == floorSqrt * floorSqrt);}Â
// Function that returns true check // if N is sum of three squaresstatic bool legendreFunction(int N){Â Â Â Â Â Â Â Â Â // Factor out the powers of 4Â Â Â Â while (N % 4 == 0)Â Â Â Â Â Â Â Â N /= 4;Â
    // N is NOT of the    // form 4^a * (8b + 7)    if (N % 8 != 7)        return true;    else        return false;}Â
// Function that finds the minimum// number of square whose sum is Nstatic int minSquares(int N){Â
    // If N is perfect square    if (isPerfectSquare(N))        return 1;Â
    // If N is sum of 2 perfect squares    for(int i = 1; i * i < N; i++)     {        if (isPerfectSquare(N - i * i))            return 2;    }Â
    // If N is sum of 3 perfect squares    if (legendreFunction(N))        return 3;Â
    // Otherwise, N is the    // sum of 4 perfect squares    return 4;}Â
// Driver codepublic static void Main(String[] args){         // Given number    int N = 123;Â
    // Function call    Console.Write(minSquares(N));}}Â
// This code is contributed by Rajput-Ji |
Javascript
<script>Â
// Javascript program for the above approachÂ
// Function that returns true if N// is a perfect squarefunction isPerfectSquare(N){    let floorSqrt = Math.floor(Math.sqrt(N));       return (N == floorSqrt * floorSqrt);}   // Function that returns true check if// N is sum of three squaresfunction legendreFunction(N){           // Factor out the powers of 4    while (N % 4 == 0)        N = Math.floor(N / 4);       // N is NOT of the    // form 4^a * (8b + 7)    if (N % 8 != 7)        return true;    else        return false;}   // Function that finds the minimum// number of square whose sum is Nfunction minSquares(N){       // If N is perfect square    if (isPerfectSquare(N))        return 1;       // If N is sum of 2 perfect squares    for(let i = 1; i * i < N; i++)     {        if (isPerfectSquare(N - i * i))            return 2;    }       // If N is sum of 3 perfect squares    if (legendreFunction(N))        return 3;       // Otherwise, N is the    // sum of 4 perfect squares    return 4;}Â
// Driver CodeÂ
    // Given number    let N = 123;       // Function call    document.write(minSquares(N));Â
</script> |
3
Time Complexity: O(sqrt(N))
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!


