Minimum number of squares whose sum equals to given number n

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 X.
Examples : 

Input:  n = 100
Output: 1
100 can be written as 102. Note that 100 can also be 
written as 52 + 52 + 52 + 52, but this
representation requires 4 squares.

Input:  n = 6
Output: 3

The idea is simple, we start from 1 and go till a number whose square is smaller than or equals to n. For every number x, we recur for n-x. Below is the recursive formula. 

If n = 1 and x*x <= n 

Below is a simple recursive solution based on above recursive formula. 

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// A naive recursive C++
// program to find minimum
// number of squares whose sum
// is equal to a given number
#include <bits/stdc++.h>
using namespace std;
 
// Returns count of minimum
// squares that sum to n
int getMinSquares(unsigned int n)
{
    // base cases
    // if n is perfect square then
    // Minimum squares required is 1
    // (144 = 12^2)
    if (sqrt(n) - floor(sqrt(n)) == 0)
        return 1;
    if (n <= 3)
        return n;
 
    // getMinSquares rest of the
    // table using recursive
    // formula
    // Maximum squares required
    // is n (1*1 + 1*1 + ..)
    int res = n;
 
    // Go through all smaller numbers
    // to recursively find minimum
    for (int x = 1; x <= n; x++)
    {
        int temp = x * x;
        if (temp > n)
            break;
        else
            res = min(res, 1 + getMinSquares
                                  (n - temp));
    }
    return res;
}
 
// Driver program
int main()
{
    cout << getMinSquares(6);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// A naive recursive JAVA
// program to find minimum
// number of squares whose
// sum is equal to a given number
class squares
{
     
    // Returns count of minimum
    // squares that sum to n
    static int getMinSquares(int n)
    {
         
        // base cases
        if (n <= 3)
            return n;
 
        // getMinSquares rest of the
        // table using recursive
        // formula
        // Maximum squares required is
        int res = n;
        // n (1*1 + 1*1 + ..)
 
        // Go through all smaller numbers
        // to recursively find minimum
        for (int x = 1; x <= n; x++)
        {
            int temp = x * x;
            if (temp > n)
                break;
            else
                res = Math.min(res, 1 +
                          getMinSquares(n - temp));
        }
        return res;
    }
    public static void main(String args[])
    {
        System.out.println(getMinSquares(6));
    }
}
/* This code is contributed by Rajat Mishra */

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# A naive recursive Python program to
# find minimum number of squares whose
# sum is equal to a given number
 
# Returns count of minimum squares
# that sum to n
def getMinSquares(n):
 
    # base cases
    if n <= 3:
        return n;
 
    # getMinSquares rest of the table
    # using recursive formula
    # Maximum squares required
    # is n (1 * 1 + 1 * 1 + ..)
    res = n
 
    # Go through all smaller numbers
    # to recursively find minimum
    for x in range(1, n + 1):
        temp = x * x;
        if temp > n:
            break
        else:
            res = min(res, 1 + getMinSquares(n
                                  - temp))
     
    return res;
 
# Driver program
print(getMinSquares(6))
 
# This code is contributed by nuclode

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// A naive recursive C# program
// to find minimum number of
// squares whose sum is equal
// to a given number
using System;
 
class GFG
{
 
    // Returns count of minimum
    // squares that sum to n
    static int getMinSquares(int n)
    {
 
        // base cases
        if (n <= 3)
            return n;
 
        // getMinSquares rest of the
        // table using recursive
        // formula
 
        // Maximum squares required is
        // n (1*1 + 1*1 + ..)
        int res = n;
 
        // Go through all smaller numbers
        // to recursively find minimum
        for (int x = 1; x <= n; x++)
        {
            int temp = x * x;
            if (temp > n)
                break;
            else
                res = Math.Min(res, 1 +
                      getMinSquares(n - temp));
        }
        return res;
    }
 
    // Driver Code
    public static void Main()
    {
        Console.Write(getMinSquares(6));
    }
}
 
// This code is contributed by nitin mittal

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// A naive recursive PHP program
// to find minimum number of
// squares whose sum is equal
// to a given number
 
// Returns count of minimum
// squares that sum to n
function getMinSquares($n)
{
    // base cases
    if ($n <= 3)
        return $n;
 
    // getMinSquares rest of the
    // table using recursive formula
     
    // Maximum squares required
    // is n (1*1 + 1*1 + ..)
    $res = $n;
 
    // Go through all smaller numbers
    // to recursively find minimum
    for ($x = 1; $x <= $n; $x++)
    {
        $temp = $x * $x;
        if ($temp > $n)
            break;
        else
            $res = min($res, 1 +
                       getMinSquares($n -
                                     $temp));
    }
    return $res;
}
 
// Driver Code
echo getMinSquares(6);
 
// This code is contributed
// by nitin mittal.
?>

chevron_right


Output : 

3

The time complexity of above solution is exponential. If we draw the complete recursion tree, we can observer that many subproblems are solved again and again. For example, when we start from n = 6, we can reach 4 by subtracting one 2 times and by subtracting 2 one times. So the subproblem for 4 is called twice.
Since same suproblems are called again, this problem has Overlapping Subprolems property. So min square sum problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided by constructing a temporary array table[][] in bottom up manner. Below is Dynamic Programming based solution
 



C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// A dynamic programming based
// C++ program to find minimum
// number of squares whose sum
// is equal to a given number
#include <bits/stdc++.h>
using namespace std;
 
// Returns count of minimum
// squares that sum to n
int getMinSquares(int n)
{
     
    // Create a dynamic
    // programming table
    // to store sq
    int* dp = new int[n + 1];
 
    // getMinSquares table
    // for base case entries
    dp[0] = 0;
    dp[1] = 1;
    dp[2] = 2;
    dp[3] = 3;
 
    // getMinSquares rest of the
    // table using recursive
    // formula
    for (int i = 4; i <= n; i++)
    {
         
        // max value is i as i can
        // always be represented
        // as 1*1 + 1*1 + ...
        dp[i] = i;
 
        // Go through all smaller numbers to
        // to recursively find minimum
        for (int x = 1; x <= ceil(sqrt(i)); x++)
        {
            int temp = x * x;
            if (temp > i)
                break;
            else
                dp[i] = min(dp[i], 1 +
                                  dp[i - temp]);
        }
    }
 
    // Store result and free dp[]
    int res = dp[n];
    delete[] dp;
 
    return res;
}
 
// Driver program
int main()
{
    cout << getMinSquares(6);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// A dynamic programming based
// JAVA program to find minimum
// number of squares whose sum
// is equal to a given number
class squares
{
 
    // Returns count of minimum
    // squares that sum to n
    static int getMinSquares(int n)
    {
 
        // We need to add a check
        // here for n. If user enters
        // 0 or 1 or 2
        // the below array creation
        // will go OutOfBounds.
        if (n <= 3)
            return n;
 
        // Create a dynamic programming
        // table
        // to store sq
        int dp[] = new int[n + 1];
 
        // getMinSquares table for
        // base case entries
        dp[0] = 0;
        dp[1] = 1;
        dp[2] = 2;
        dp[3] = 3;
 
        // getMinSquares rest of the
        // table using recursive
        // formula
        for (int i = 4; i <= n; i++)
        {
         
            // max value is i as i can
            // always be represented
            // as 1*1 + 1*1 + ...
            dp[i] = i;
 
            // Go through all smaller numbers to
            // to recursively find minimum
            for (int x = 1; x <= Math.ceil(
                              Math.sqrt(i)); x++)
            {
                int temp = x * x;
                if (temp > i)
                    break;
                else
                    dp[i] = Math.min(dp[i], 1
                                  + dp[i - temp]);
            }
        }
 
        // Store result and free dp[]
        int res = dp[n];
 
        return res;
    }
   
    // Driver Code
    public static void main(String args[])
    {
        System.out.println(getMinSquares(6));
    }
} /* This code is contributed by Rajat Mishra */

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# A dynamic programming based Python
# program to find minimum number of
# squares whose sum is equal to a
# given number
from math import ceil, sqrt
 
# Returns count of minimum squares
# that sum to n
def getMinSquares(n):
 
    # Create a dynamic programming table
    # to store sq and getMinSquares table
    # for base case entries
    dp = [0, 1, 2, 3]
 
    # getMinSquares rest of the table
    # using recursive formula
    for i in range(4, n + 1):
         
        # max value is i as i can always
        # be represented as 1 * 1 + 1 * 1 + ...
        dp.append(i)
 
        # Go through all smaller numbers
        # to recursively find minimum
        for x in range(1, int(ceil(sqrt(i))) + 1):
            temp = x * x;
            if temp > i:
                break
            else:
                dp[i] = min(dp[i], 1 + dp[i-temp])
 
    # Store result
    return dp[n]
 
# Driver program
print(getMinSquares(6))
 
# This code is contributed by nuclode

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// A dynamic programming based
// C# program to find minimum
// number of squares whose sum
// is equal to a given number
using System;
 
class squares
{
 
    // Returns count of minimum
    // squares that sum to n
    static int getMinSquares(int n)
    {
 
        // We need to add a check here
        // for n. If user enters 0 or 1 or 2
        // the below array creation will go
        // OutOfBounds.
 
        if (n <= 3)
            return n;
 
        // Create a dynamic programming
        // table to store sq
        int[] dp = new int[n + 1];
 
        // getMinSquares table for base
        // case entries
        dp[0] = 0;
        dp[1] = 1;
        dp[2] = 2;
        dp[3] = 3;
 
        // getMinSquares for rest of the
        // table using recursive formula
        for (int i = 4; i <= n; i++)
        {
         
            // max value is i as i can
            // always be represented
            // as 1 * 1 + 1 * 1 + ...
            dp[i] = i;
 
            // Go through all smaller numbers to
            // to recursively find minimum
            for (int x = 1; x <= Math.Ceiling(
                              Math.Sqrt(i)); x++)
            {
                int temp = x * x;
                if (temp > i)
                    break;
                else
                    dp[i] = Math.Min(dp[i], 1 +
                                    dp[i - temp]);
            }
        }
 
        // Store result and free dp[]
        int res = dp[n];
 
        return res;
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        Console.Write(getMinSquares(6));
    }
}
 
// This code is contributed by Nitin Mittal.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// A dynamic programming based
// PHP program to find minimum
// number of squares whose sum
// is equal to a given number
 
// Returns count of minimum
// squares that sum to n
function getMinSquares($n)
{
     
    // Create a dynamic programming
    // table to store sq
    $dp;
 
    // getMinSquares table for
    // base case entries
    $dp[0] = 0;
    $dp[1] = 1;
    $dp[2] = 2;
    $dp[3] = 3;
 
    // getMinSquares rest of the
    // table using recursive formula
    for ($i = 4; $i <= $n; $i++)
    {
        // max value is i as i can
        // always be represented
        // as 1*1 + 1*1 + ...
        $dp[$i] = $i;
 
        // Go through all smaller
        // numbers to recursively
        // find minimum
        for ($x = 1; $x <= ceil(sqrt($i));
                                     $x++)
        {
            $temp = $x * $x;
            if ($temp > $i)
                break;
            else $dp[$i] = min($dp[$i],
                       (1 + $dp[$i - $temp]));
        }
    }
 
    // Store result
    // and free dp[]
    $res = $dp[$n];
 
    // delete $dp;
    return $res;
}
 
// Driver Code
echo getMinSquares(6);
     
// This code is contributed
// by shiv_bhakt.
?>

chevron_right


Output: 

3

Thanks to Gaurav Ahirwar for suggesting this solution.

Another Approach:
This problem can also be solved by using graph.Here is the basic idea how it can be done 
We will use BFS(Breadth First Search) to find the minimum number of steps from given value of n to 0. 
So for every node, we will push its next possible valid path which is not visited yet into a queue and, 
and if it reaches the node 0, we will update our answer if it less than the answer. 
 Below is the implementation of the above approach:

CPP

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to count minimum
// squares that sum to n
int numSquares(int n)
{
  
  // Creating visited vector
  // of size n + 1
  vector<int> visited(n + 1,0);
   
  // Queue of pair to store node
  // and number of steps
  queue< pair<int,int> >q;
   
  // Initially ans variable is
  // initialized with inf
  int ans = INT_MAX;
   
  // Push starting node with 0
  // 0 indicate current number
  // of step to reach n
  q.push({n,0});
   
  // Mark starting node visited
  visited[n] = 1;
  while(!q.empty())
  {
    pair<int,int> p;
    p = q.front();
    q.pop();
 
    // If node reaches its destination
    // 0 update it with answer
    if(p.first == 0)
      ans=min(ans, p.second);
 
    // Loop for all possible path from
    // 1 to i*i <= current node(p.first)
    for(int i = 1; i * i <= p.first; i++)
    {
       
      // If we are standing at some node
      // then next node it can jump to will
      // be current node-
      // (some square less than or equal n)
      int path=(p.first - (i*i));
 
      // Check if it is valid and
      // not visited yet
      if(path >= 0 && ( !visited[path]
                             || path == 0))
      {
         
        // Mark visited
        visited[path]=1;
         
        // Push it it Queue
        q.push({path,p.second + 1});
      }
    }
  }
   
  // Return ans to calling function
  return ans;
}
 
// Driver program
int main()
{
  cout << numSquares(12);
  return 0;
}

chevron_right


Output: 

3

The time complexity of the above problem is O(n)*sqrt(n) which is better than the Recursive approach 
Also it is great to way to understand how BFS(Breadth First Search) work
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up