Minimum perfect squares to add that sum to given number.
Last Updated :
23 Jul, 2025
Given a positive integer n, the task is to find the minimum number of squares that sum to n.
Note: A number can always be represented as a sum of squares of other numbers. Because 1 is a square number and we can always break any number as (1*1 + 1*1 + 1*1 + ... ).
Examples :
Input: n = 100
Output: 1
Explanation: 100 can be written as [ 102 ] or [ 52 + 52 + 52 + 52 ] and the smallest square numbers needed is 1, in case [ 102 ].
Input: n = 6
Output: 3
Explanation: Only possible way to write 6 as sum of squares is [ 12 + 12 + 22 ], so minimum square numbers needed is 3.
Using Recursion
We can easily identify the recursive nature of this problem. We can form the sum n as (x^2 + (n - x^2)) for various values of x, such that x2 <= n. To find the minimum number of squares needed to form the sum n, we use the formula:
minSquares(n) = min( 1 + minSquares(n - x2) ), for all x where x2 <= n.
Base Case: minSquares(n) = 1, if n itself is a square number
C++
// C++ program to find minimum number of squares whose
// sum is equal to a given number using recursion
#include <iostream>
using namespace std;
// Function to find count of minimum squares
// that sum to n
int minSquares(int n) {
// base case: minSquares(1) = 1
// minSquares(2) = 2
// minSquares(3) = 3
if (n <= 3)
return n;
// Any positive number n, can be represented
// as sum of 1*1 + 1*1 .... n times
// so we can initialise count with n
int cnt = n;
// Go through all smaller numbers
// to recursively find minimum
for (int x = 1; x*x <= n; x++) {
cnt = min(cnt, 1 + minSquares(n - x*x));
}
return cnt;
}
int main() {
int n = 6;
cout << minSquares(n);
return 0;
}
C
// C program to find minimum number of squares whose
// sum is equal to a given number using recursion
#include <stdio.h>
// Function to find count of minimum squares
// that sum to n
int minSquares(int n) {
// base case: minSquares(1) = 1
// minSquares(2) = 2
// minSquares(3) = 3
if (n <= 3)
return n;
// Any positive number n, can be represented
// as sum of 1*1 + 1*1 .... n times
// so we can initialise count with n
int cnt = n;
// Go through all smaller numbers
// to recursively find minimum
for (int x = 1; x*x <= n; x++) {
cnt = fmin(cnt, 1 + minSquares(n - x*x));
}
return cnt;
}
int main() {
int n = 6;
printf("%d", minSquares(n));
return 0;
}
Java
// Java program to find minimum number of squares whose
// sum is equal to a given number using recursion
class GfG {
// Function to find count of minimum squares
// that sum to n
static int minSquares(int n) {
// base case: minSquares(1) = 1
// minSquares(2) = 2
// minSquares(3) = 3
if (n <= 3)
return n;
// Any positive number n, can be represented
// as sum of 1*1 + 1*1 .... n times
// so we can initialise count with n
int cnt = n;
// Go through all smaller numbers
// to recursively find minimum
for (int x = 1; x * x <= n; x++) {
cnt = Math.min(cnt, 1 + minSquares(n - x * x));
}
return cnt;
}
public static void main(String[] args) {
int n = 6;
System.out.println(minSquares(n));
}
}
Python
# C++ program to find minimum number of squares whose
# sum is equal to a given number using recursion
import math
# Function to find count of minimum squares
# that sum to n
def minSquares(n):
# base case: minSquares(1) = 1
# minSquares(2) = 2
# minSquares(3) = 3
if n <= 3:
return n
# Any positive number n, can be represented
# as sum of 1*1 + 1*1 .... n times
# so we can initialise count with n
cnt = n
# Go through all smaller numbers
# to recursively find minimum
for x in range(1, int(math.sqrt(n)) + 1):
cnt = min(cnt, 1 + minSquares(n - x * x))
return cnt
if __name__ == "__main__":
n = 6
print(minSquares(n))
C#
// C# program to find minimum number of squares whose
// sum is equal to a given number using recursion
using System;
class GfG {
// Function to find count of minimum squares
// that sum to n
static int minSquares(int n) {
// base case: minSquares(1) = 1
// minSquares(2) = 2
// minSquares(3) = 3
if (n <= 3)
return n;
// Any positive number n can be represented
// as sum of 1*1 + 1*1 .... n times
// so we initialize count with n
int cnt = n;
// Go through all smaller numbers
// to recursively find minimum
for (int x = 1; x * x <= n; x++) {
cnt = Math.Min(cnt, 1 + minSquares(n - x * x));
}
return cnt;
}
static void Main() {
int n = 6;
Console.WriteLine(minSquares(n));
}
}
JavaScript
// JavaScript program to find count of minimum squares
// that sum to n
// Function to find count of minimum squares
// that sum to n
function minSquares(n) {
// base case: minSquares(1) = 1
// minSquares(2) = 2
// minSquares(3) = 3
if (n <= 3)
return n;
// Any positive number n, can be represented
// as sum of 1*1 + 1*1 .... n times
// so we can initialise count with n
let cnt = n;
// Go through all smaller numbers
// to recursively find minimum
for (let x = 1; x * x <= n; x++) {
cnt = Math.min(cnt, 1 + minSquares(n - x * x));
}
return cnt;
}
const n = 6;
console.log(minSquares(n));
Note: The time complexity of the above solution is exponential.
Using Top-Down DP (Memoization)
If we notice carefully, we can observe that this recursive solution holds the following two properties of Dynamic Programming:
1. Optimal Substructure:
Minimum perfect squares that add to n. i.e., minSquares(n), depends on the optimal solutions of the subproblems minSquares(n - x2). By finding these optimal substructures, we can efficiently calculate the minimum perfect squares that sum to given number.
2. Overlapping Subproblems:
While applying a recursive approach in this problem, we notice that certain subproblems are computed multiple times. For example, when calculating minSquares(6), we recursively calculate minSquares(5) and minSquares(2), which in turn will recursively compute minSquares(2) again. This redundancy leads to overlapping subproblems.
C++
// C++ program to find minimum number of squares whose
// sum is equal to a given number using memoization
#include <iostream>
#include <vector>
using namespace std;
// Function to find count of minimum squares
// that sum to n
int minSquaresRec(int n, vector<int>& memo) {
// base case: minSquares(1) = 1
// minSquares(2) = 2
// minSquares(3) = 3
if (n <= 3)
return n;
// if the result for this subproblem is
// already computed then return it
if (memo[n] != -1)
return memo[n];
// Any positive number n, can be represented
// as sum of 1*1 + 1*1 .... n times
// so we can initialise count with n
int cnt = n;
// Go through all smaller numbers
// to recursively find minimum
for (int x = 1; x*x <= n; x++) {
cnt = min(cnt, 1 + minSquaresRec(n - x*x, memo));
}
// store the result of this problem
// to avoid re computation
return memo[n] = cnt;
}
int minSquares(int n) {
// Memoization array to store the results
vector<int> memo(n + 1, -1);
return minSquaresRec(n, memo);
}
int main() {
int n = 6;
cout << minSquares(n);
return 0;
}
Java
// Java program to find minimum number of squares whose
// sum is equal to a given number using memoization
import java.util.Arrays;
class GfG {
// Function to find count of minimum
// squares that sum to n
static int minSquaresRec(int n, int[] memo) {
// base case: minSquares(1) = 1
// minSquares(2) = 2
// minSquares(3) = 3
if (n <= 3)
return n;
// if the result for this subproblem is
// already computed then return it
if (memo[n] != -1)
return memo[n];
// Any positive number n, can be represented
// as sum of 1*1 + 1*1 .... n times
// so we can initialise count with n
int cnt = n;
// Go through all smaller numbers to
// recursively find minimum
for (int x = 1; x * x <= n; x++) {
cnt = Math.min(cnt, 1 + minSquaresRec(n - x * x, memo));
}
// store the result of this problem to
// avoid re computation
return memo[n] = cnt;
}
static int minSquares(int n) {
// Memoization array to store
// the results
int[] memo = new int[n + 1];
Arrays.fill(memo, -1);
return minSquaresRec(n, memo);
}
public static void main(String[] args) {
int n = 6;
System.out.println(minSquares(n));
}
}
Python
# Python program to find minimum number of squares whose
# sum is equal to a given number using memoization
def minSquaresRec(n, memo):
# base case: minSquares(1) = 1
# minSquares(2) = 2
# minSquares(3) = 3
if n <= 3:
return n
# if the result for this subproblem is already
# computed then return it
if memo[n] != -1:
return memo[n]
# Any positive number n, can be represented
# as sum of 1*1 + 1*1 .... n times
# so we can initialise count with n
cnt = n
# Go through all smaller numbers to recursively
# find minimum
for x in range(1, int(n**0.5) + 1):
cnt = min(cnt, 1 + minSquaresRec(n - x * x, memo))
# store the result of this problem to avoid re computation
memo[n] = cnt
return cnt
def minSquares(n):
# Memoization array to store the results
memo = [-1] * (n + 1)
return minSquaresRec(n, memo)
if __name__ == "__main__":
n = 6
print(minSquares(n))
C#
// C# program to find minimum number of squares whose
// sum is equal to a given number using memoization
using System;
class GfG {
// Function to find count of minimum squares that sum to n
static int minSquaresRec(int n, int[] memo) {
// base case: minSquares(1) = 1
// minSquares(2) = 2
// minSquares(3) = 3
if (n <= 3)
return n;
// if the result for this subproblem is already
// computed then return it
if (memo[n] != -1)
return memo[n];
// Any positive number n, can be represented as
// sum of 1*1 + 1*1 .... n times
// so we can initialise count with n
int cnt = n;
// Go through all smaller numbers to
// recursively find minimum
for (int x = 1; x * x <= n; x++) {
cnt = Math.Min(cnt, 1 +
minSquaresRec(n - x * x, memo));
}
// store the result of this problem to
// avoid re computation
return memo[n] = cnt;
}
static int minSquares(int n) {
// Memoization array to store the results
int[] memo = new int[n + 1];
Array.Fill(memo, -1);
return minSquaresRec(n, memo);
}
static void Main() {
int n = 6;
Console.WriteLine(minSquares(n));
}
}
JavaScript
// JavaScript program to find minimum number of squares whose
// sum is equal to a given number using memoization
// Function to find count of minimum squares that sum to n
function minSquaresRec(n, memo) {
// base case: minSquares(1) = 1
// minSquares(2) = 2
// minSquares(3) = 3
if (n <= 3)
return n;
// if the result for this subproblem is already
// computed then return it
if (memo[n] !== -1)
return memo[n];
// Any positive number n, can be represented
// as sum of 1*1 + 1*1 .... n times
// so we can initialise count with n
let cnt = n;
// Go through all smaller numbers to
// recursively find minimum
for (let x = 1; x * x <= n; x++) {
cnt = Math.min(cnt, 1 +
minSquaresRec(n - x * x, memo));
}
// store the result of this problem
// to avoid re computation
return memo[n] = cnt;
}
function minSquares(n) {
// Memoization array to store the results
const memo = Array(n + 1).fill(-1);
return minSquaresRec(n, memo);
}
const n = 6;
console.log(minSquares(n));
Time Complexity: O(n*sqrt(n)), as we compute each subproblem only once using memoization.
Auxiliary Space: O(n)
Using Bottom-Up DP (Tabulation)
The approach is similar to the previous one; just instead of breaking down the problem recursively, we iteratively build up the solution by calculating in bottom-up manner. Maintain a dp[] table such that dp[i] stores the minimum perfect squares that sum to i.
- Base Case: For i = 0 and i = 1, dp[i] = i
- Recursive Case: For i > 1, dp[i] = min( 1 + dp[i - x2] ), for all x such that x * x <= i.
C++
// C++ program to find minimum number of squares whose
// sum is equal to a given number Using Bottom-Up DP
#include <iostream>
#include <vector>
using namespace std;
int minSquares(int n) {
// Memoization array to store the results
vector<int> dp(n + 1);
// base case
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = i;
for (int x = 1; x * x <= i; ++x) {
// recursive case
dp[i] = min(dp[i], 1 + dp[i - x*x]);
}
}
return dp[n];
}
int main() {
int n = 6;
cout << minSquares(n);
return 0;
}
Java
// Java program to find minimum number of squares whose
// sum is equal to a given number Using Bottom-Up DP
import java.util.Arrays;
class GfG {
static int minSquares(int n) {
// Memoization array to store the results
int[] dp = new int[n + 1];
// base case
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = i;
for (int x = 1; x * x <= i; ++x) {
// recursive case
dp[i] = Math.min(dp[i], 1 + dp[i - x * x]);
}
}
return dp[n];
}
public static void main(String[] args) {
int n = 6;
System.out.println(minSquares(n));
}
}
Python
# Python program to find minimum number of squares whose
# sum is equal to a given number Using Bottom-Up DP
def minSquares(n):
# Memoization array to store the results
dp = [0] * (n + 1)
# base case
dp[0] = 0
dp[1] = 1
for i in range(2, n + 1):
dp[i] = i
for x in range(1, int(i**0.5) + 1):
# recursive case
dp[i] = min(dp[i], 1 + dp[i - x * x])
return dp[n]
if __name__ == "__main__":
n = 6
print(minSquares(n))
C#
// C# program to find minimum number of squares whose
// sum is equal to a given number Using Bottom-Up DP
using System;
class GfG {
static int minSquares(int n) {
// Memoization array to store the results
int[] dp = new int[n + 1];
// base case
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = i;
for (int x = 1; x * x <= i; ++x) {
// recursive case
dp[i] = Math.Min(dp[i], 1 + dp[i - x * x]);
}
}
return dp[n];
}
static void Main() {
int n = 6;
Console.WriteLine(minSquares(n));
}
}
JavaScript
// JavaScript program to find minimum number of squares whose
// sum is equal to a given number Using Bottom-Up DP
function minSquares(n) {
// Memoization array to store the results
let dp = new Array(n + 1);
// base case
dp[0] = 0;
dp[1] = 1;
for (let i = 2; i <= n; i++) {
dp[i] = i;
for (let x = 1; x * x <= i; x++) {
// recursive case
dp[i] = Math.min(dp[i], 1 + dp[i - x * x]);
}
}
return dp[n];
}
// Driver Code
let n = 6;
console.log(minSquares(n));
Time Complexity: O(n*sqrt(n))
Auxiliary Space: O(n), used for dp[] array.
Using Breadth-First Search
This problem can also be solved by using graphs. We will use BFS (Breadth-First Search) to find the minimum number of steps from a given value of n to 0. So, for every node, we will push the next possible valid path which is not visited yet into a queue and if it reaches node 0, we will update our answer if it is less than the answer.
C++
// C++ program to find minimum number of squares
// whose sum is equal to a given number
// Using Breadth-First Search
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int minSquares(int n) {
// Creating visited vector of size n + 1
vector<int> vis(n + 1, 0);
int res = n;
// Queue of pair to store node
// and number of steps
queue<pair<int, int>> q;
// Push starting node with 0
// 0 indicate current number
// of step to reach n
q.push({n, 0});
// Mark starting node visited
vis[n] = 1;
while (!q.empty()) {
pair<int, int> p = q.front();
q.pop();
int node = p.first;
int steps = p.second;
// If node reaches its destination
// 0 update it with answer
if (node == 0)
res = min(res, steps);
// Loop for all possible path from
// 1 to i*i <= current node
for (int i = 1; i * i <= node; 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 = (node - (i * i));
// Check if it is valid and
// not visited yet
if (path >= 0 && (!vis[path] || path == 0)) {
// Mark visited
vis[path] = 1;
// Push it it Queue
q.push({path, steps + 1});
}
}
}
return res;
}
int main() {
int n = 6;
cout << minSquares(n);
return 0;
}
Java
// Java program to find minimum number of squares
// whose sum is equal to a given number
// Using Breadth-First Search
import java.util.*;
class GfG {
static int minSquares(int n) {
// Creating visited array of size n + 1
boolean[] vis = new boolean[n + 1];
int res = n;
// Queue of pair to store node and number
// of steps
Queue<int[]> q = new LinkedList<>();
// Push starting node with 0
// 0 indicate current number of step to reach n
q.add(new int[]{n, 0});
// Mark starting node visited
vis[n] = true;
while (!q.isEmpty()) {
int[] p = q.poll();
int node = p[0];
int steps = p[1];
// If node reaches its destination 0
// update answer
if (node == 0)
res = Math.min(res, steps);
// Loop for all possible path
// from 1 to i*i <= current node
for (int i = 1; i * i <= node; 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 = (node - (i * i));
// Check if it is valid and not visited yet
if (path >= 0 && (!vis[path] || path == 0)) {
// Mark visited
vis[path] = true;
// Push it it Queue
q.add(new int[]{path, steps + 1});
}
}
}
return res;
}
public static void main(String[] args) {
int n = 6;
System.out.println(minSquares(n));
}
}
Python
# Python program to find minimum number of squares
# whose sum is equal to a given number
# Using Breadth-First Search
from collections import deque
def minSquares(n):
# Creating visited array of size n + 1
vis = [0] * (n + 1)
res = n
# Queue of pair to store node and number
# of steps
q = deque()
# Push starting node with 0
# 0 indicate current number of step to reach n
q.append((n, 0))
# Mark starting node visited
vis[n] = 1
while q:
node, steps = q.popleft()
# If node reaches its destination 0
# update it with answer
if node == 0:
res = min(res, steps)
# Loop for all possible path
# from 1 to i*i <= current node
for i in range(1, int(node**0.5) + 1):
# If we are standing at some node
# then next node it can jump to will b2
# current node - (some square less than or equal n)
path = node - (i * i)
# Check if it is valid and not visited yet
if path >= 0 and (not vis[path] or path == 0):
# Mark visited
vis[path] = 1
# Push it it Queue
q.append((path, steps + 1))
return res
if __name__ == "__main__":
n = 6
print(minSquares(n))
C#
// C# program to find minimum number of squares
// whose sum is equal to a given number
// Using Breadth-First Search
using System;
using System.Collections.Generic;
class GfG {
static int minSquares(int n) {
// Creating visited array of size n + 1
bool[] vis = new bool[n + 1];
int res = n;
// Queue of pair to store node and number
// of steps
Queue<Tuple<int, int>> q = new
Queue<Tuple<int, int>>();
// Push starting node with 0
// 0 indicate current number of step to reach n
q.Enqueue(Tuple.Create(n, 0));
// Mark starting node visited
vis[n] = true;
while (q.Count > 0) {
var p = q.Dequeue();
int node = p.Item1;
int steps = p.Item2;
// If node reaches its destination 0
// update it with answer
if (node == 0)
res = Math.Min(res, steps);
// Loop for all possible path from 1 to
// i*i <= current node
for (int i = 1; i * i <= node; 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 = node - (i * i);
// Check if it is valid and not visited yet
if (path >= 0 && (!vis[path] || path == 0)) {
// Mark visited
vis[path] = true;
// Push it it Queue
q.Enqueue(Tuple.Create(path, steps + 1));
}
}
}
return res;
}
static void Main() {
int n = 6;
Console.WriteLine(minSquares(n));
}
}
JavaScript
// JavaScript program to find minimum number of
// squares whose sum is equal to a given number
// Using Breadth-First Search
function minSquares(n) {
// Creating visited array of size n + 1
const vis = new Array(n + 1).fill(0);
let res = n;
// Queue of pair to store node and number of steps
const q = [];
// Push starting node with 0
// 0 indicate current number of step to reach n
q.push([n, 0]);
// Mark starting node visited
vis[n] = 1;
while (q.length) {
const [node, steps] = q.shift();
// If node reaches its destination 0
// update it with answer
if (node === 0)
res = Math.min(res, steps);
// Loop for all possible path
// from 1 to i*i <= current node
for (let i = 1; i * i <= node; 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)
const path = node - (i * i);
// Check if it is valid and not visited yet
if (path >= 0 && (!vis[path] || path === 0)) {
// Mark visited
vis[path] = 1;
// Push it it Queue
q.push([path, steps + 1]);
}
}
}
return res;
}
const n = 6;
console.log(minSquares(n));
Time Complexity: O(n*sqrt(n))
Auxiliary Space: O(n), used for queue and visited array.
Bottom-up approach similar to Unbounded knapsack
This problem can also be solved using Dynamic programming (Bottom-up approach). The idea is like coin change 2 (in which we need to tell minimum number of coins to make an amount from given coins[] array), here an array of all perfect squares less than or equal to n can be replaced by coins[] array and amount can be replaced by n. Please refer to unbounded knapsack problem.
Below is the implementation of the above approach:
C++
// C++ program to find minimum number of squares
// whose sum is equal to a given number
// Using Unbounded Knapsack Concept
#include <iostream>
#include <vector>
using namespace std;
// Function to count minimum
// squares that sum to n
int minSquares(int n) {
//Making the array of perfect squares
// less than or equal to n
vector<int> arr;
int i = 1;
while(i*i <= n){
arr.push_back(i*i);
i++;
}
//A dp array which will store minimum number
// of perfect squares required to make n
// from i at i th index
vector<int> dp(n+1, n);
dp[n] = 0;
for(int i = n - 1; i >= 0; i--){
//checking from i th value to n value
// minimum perfect squares required
for(int j = 0; j < arr.size(); j++){
//check if index doesn't goes out of bound
if(i + arr[j] <= n){
dp[i] = min(dp[i], dp[i+arr[j]]);
}
}
//from current to go to min step one
// i we need to take one step
dp[i]++;
}
return dp[0];
}
int main() {
int n = 6;
cout << minSquares(n);
return 0;
}
Java
// Java program to find minimum number of squares
// whose sum is equal to a given number
// Using Unbounded Knapsack Concept
import java.util.ArrayList;
class GfG {
// Function to count minimum
// squares that sum to n
static int minSquares(int n) {
// Making the array of perfect squares
// less than or equal to n
ArrayList<Integer> arr = new ArrayList<>();
int i = 1;
while (i * i <= n) {
arr.add(i * i);
i++;
}
// A dp array which will store minimum number
// of perfect squares required to make n
// from i at i th index
int[] dp = new int[n + 1];
for (i = 1; i <= n; i++) {
dp[i] = n;
}
dp[0] = 0;
for (i = 1; i <= n; i++) {
for (int j = 0; j < arr.size(); j++) {
if (i >= arr.get(j)) {
dp[i] = Math.min(dp[i],
dp[i - arr.get(j)] + 1);
}
}
}
return dp[n];
}
public static void main(String[] args) {
int n = 6;
System.out.println(minSquares(n));
}
}
Python
# Python program to find minimum number of squares
# whose sum is equal to a given number
# Using Unbounded Knapsack Concept
def minSquares(n):
# Making the array of perfect squares
# less than or equal to n
arr = []
i = 1
while i * i <= n:
arr.append(i * i)
i += 1
# A dp array which will store minimum number
# of perfect squares required to make n
# from i at i th index
dp = [n] * (n + 1)
dp[0] = 0
for i in range(1, n + 1):
for j in range(len(arr)):
if i >= arr[j]:
dp[i] = min(dp[i], dp[i - arr[j]] + 1)
return dp[n]
if __name__ == '__main__':
n = 6
print(minSquares(n))
C#
// C# program to find minimum number of squares
// whose sum is equal to a given number
// Using Unbounded Knapsack Concept
using System;
using System.Collections.Generic;
class GfG {
// Function to count minimum
// squares that sum to n
static int minSquares(int n) {
// Making the array of perfect squares
// less than or equal to n
List<int> arr = new List<int>();
int i = 1;
while (i * i <= n) {
arr.Add(i * i);
i++;
}
// A dp array which will store minimum number
// of perfect squares required to make n
// from i at i th index
int[] dp = new int[n + 1];
for (i = 1; i <= n; i++) {
dp[i] = n;
}
dp[0] = 0;
for (i = 1; i <= n; i++) {
foreach (int square in arr) {
if (i >= square) {
dp[i] = Math.Min(dp[i], dp[i - square] + 1);
}
}
}
return dp[n];
}
static void Main() {
int n = 6;
Console.WriteLine(minSquares(n));
}
}
JavaScript
// JavsScript program to find minimum number of squares
// whose sum is equal to a given number
// Using Unbounded Knapsack Concept
function minSquares(n) {
// Making the array of perfect squares
// less than or equal to n
let arr = [];
let i = 1;
while (i * i <= n) {
arr.push(i * i);
i++;
}
// A dp array which will store minimum number
// of perfect squares required to make n
// from i at i th index
let dp = new Array(n + 1).fill(n);
dp[n] = 0;
for (let i = n - 1; i >= 0; i--) {
// checking from i th value to n value
// minimum perfect squares required
for (let j = 0; j < arr.length; j++) {
// check if index doesn't goes out of bound
if (i + arr[j] <= n) {
dp[i] = Math.min(dp[i], dp[i + arr[j]]);
}
}
// from current to go to min step one
// i we need to take one step
dp[i]++;
}
return dp[0];
}
let n = 6;
console.log(minSquares(n));
Time Complexity: O(n*sqrt(n))
Auxiliary Space: O(n), used for dp[] array.
Using Mathematics(Lagrange's Four Square Theorem)
The solution is based on Lagrange's Four Square Theorem.
According to the theorem, there can be at-most 4 solutions to this problem i.e., 1, 2, 3, 4
Case 1:
Ans = 1 => This can happen if the number itself is a square number.
n = {a2 : a ∈ W}
Example : 1, 4, 9, etc.
Case 2:
Ans = 2 => This is possible if the number is the sum of 2 square numbers.
n = {a2 + b2 : a, b ∈ W}
Example : 2, 5, 18, etc.
Case 3:
Ans = 3 => This can happen if the number is not of the form 4k(8m + 7).
n = {a2 + b2 + c2 : a, b, c ∈ W} ⟷ n ≢ {4k(8m + 7) : k, m ∈ W }
Example : 6, 11, 12 etc.
Case 4:
Ans = 4 => This can happen if the number is of the form 4k(8m + 7).
n = {a2 + b2 + c2 + d2 : a, b, c, d ∈ W} ⟷ n ≡ {4k(8m + 7) : k, m ∈ W }
Example : 7, 15, 23 etc.
C++
// C++ program to find minimum number of squares
// whose sum is equal to a given number
// Using Lagrange's Four Square Theorem
#include <iostream>
#include <cmath>
using namespace std;
// returns true if the number x is a square number,
// else returns false
bool isSquare(int x) {
int sqRoot = sqrt(x);
return (sqRoot * sqRoot == x);
}
// Function to count minimum squares that sum to n
int minSquares(int n) {
// Case 1: ans = 1 if the number itself is a
// perfect square
if (isSquare(n)) {
return 1;
}
// Case 2: ans = 2 if the number is a sum of
// two perfect square
// we check for each i if n - (i * i) is a perfect
// square
for (int i = 1; i * i <= n; i++) {
if (isSquare(n - (i * i))) {
return 2;
}
}
// Case 4: ans = 4 if the number is a sum of
// four perfect square
// possible if the number is representable in the form
// 4^a (8*b + 7).
while (n > 0 && n % 4 == 0) {
n /= 4;
}
if (n % 8 == 7) {
return 4;
}
// since all the other cases have been evaluated,
// the answer can only then be 3 if the program
// reaches here
return 3;
}
int main() {
int n = 6;
cout << minSquares(n) << endl;
return 0;
}
C
// C program to find minimum number of squares
// whose sum is equal to a given number
// Using Lagrange's Four Square Theorem
#include <stdio.h>
#include <math.h>
// returns true if the number x is a square number,
// else returns false
int isSquare(int x) {
int sqRoot = sqrt(x);
return (sqRoot * sqRoot == x);
}
// Function to count minimum squares that sum to n
int minSquares(int n) {
// Case 1: ans = 1 if the number itself is a
// perfect square
if (isSquare(n)) {
return 1;
}
// Case 2: ans = 2 if the number is a sum of
// two perfect square
// we check for each i if n - (i * i) is a perfect
// square
for (int i = 1; i * i <= n; i++) {
if (isSquare(n - (i * i))) {
return 2;
}
}
// Case 4: ans = 4 if the number is a sum of
// four perfect square
// possible if the number is representable in the form
// 4^a (8*b + 7).
while (n > 0 && n % 4 == 0) {
n /= 4;
}
if (n % 8 == 7) {
return 4;
}
// since all the other cases have been evaluated,
// the answer can only then be 3 if the program
// reaches here
return 3;
}
int main() {
int n = 6;
printf("%d\n", minSquares(n));
return 0;
}
Java
// Java program to find minimum number of squares
// whose sum is equal to a given number
// Using Lagrange's Four Square Theorem
class GfG {
// returns true if the number x is a square number,
// else returns false
static boolean isSquare(int x) {
int sqRoot = (int) Math.sqrt(x);
return (sqRoot * sqRoot == x);
}
// Function to count minimum squares that sum to n
static int minSquares(int n) {
// Case 1: ans = 1 if the number itself is a
// perfect square
if (isSquare(n)) {
return 1;
}
// Case 2: ans = 2 if the number is a sum of
// two perfect square
// we check for each i if n - (i * i) is a perfect
// square
for (int i = 1; i * i <= n; i++) {
if (isSquare(n - (i * i))) {
return 2;
}
}
// Case 4: ans = 4 if the number is a sum of
// four perfect square
// possible if the number is representable in the form
// 4^a (8*b + 7).
while (n > 0 && n % 4 == 0) {
n /= 4;
}
if (n % 8 == 7) {
return 4;
}
// since all the other cases have been evaluated,
// the answer can only then be 3 if the program
// reaches here
return 3;
}
public static void main(String[] args) {
int n = 6;
System.out.println(minSquares(n));
}
}
Python
# Python program to find minimum number of squares
# whose sum is equal to a given number
# Using Lagrange's Four Square Theorem
import math
# returns true if the number x is a square number,
# else returns false
def isSquare(x):
sqRoot = int(math.sqrt(x))
return (sqRoot * sqRoot == x)
# Function to count minimum squares that sum to n
def minSquares(n):
# Case 1: ans = 1 if the number itself is a
# perfect square
if isSquare(n):
return 1
# Case 2: ans = 2 if the number is a sum of
# two perfect square
# we check for each i if n - (i * i) is a perfect
# square
for i in range(1, int(math.sqrt(n)) + 1):
if isSquare(n - (i * i)):
return 2
# Case 4: ans = 4 if the number is a sum of
# four perfect square
# possible if the number is representable in the form
# 4^a (8*b + 7).
while n > 0 and n % 4 == 0:
n //= 4
if n % 8 == 7:
return 4
# since all the other cases have been evaluated,
# the answer can only then be 3 if the program
# reaches here
return 3
if __name__ == "__main__":
n = 6
print(minSquares(n))
C#
// C# program to find minimum number of squares
// whose sum is equal to a given number
// Using Lagrange's Four Square Theorem
using System;
class GfG {
// returns true if the number x is a square number,
// else returns false
static bool isSquare(int x) {
int sqRoot = (int)Math.Sqrt(x);
return (sqRoot * sqRoot == x);
}
// Function to count minimum squares that sum to n
static int minSquares(int n) {
// Case 1: ans = 1 if the number itself is a
// perfect square
if (isSquare(n)) {
return 1;
}
// Case 2: ans = 2 if the number is a sum of
// two perfect square
// we check for each i if n - (i * i) is a perfect
// square
for (int i = 1; i * i <= n; i++) {
if (isSquare(n - (i * i))) {
return 2;
}
}
// Case 4: ans = 4 if the number is a sum of
// four perfect square
// possible if the number is representable in the form
// 4^a (8*b + 7).
while (n > 0 && n % 4 == 0) {
n /= 4;
}
if (n % 8 == 7) {
return 4;
}
// since all the other cases have been evaluated,
// the answer can only then be 3 if the program
// reaches here
return 3;
}
static void Main() {
int n = 6;
Console.WriteLine(minSquares(n));
}
}
JavaScript
// JavaScript program to find minimum number of squares
// whose sum is equal to a given number
// Using Lagrange's Four Square Theorem
// returns true if the number x is a square number,
// else returns false
function isSquare(x) {
let sqRoot = Math.floor(Math.sqrt(x));
return (sqRoot * sqRoot === x);
}
// Function to count minimum squares that sum to n
function minSquares(n) {
// Case 1: ans = 1 if the number itself is a
// perfect square
if (isSquare(n)) {
return 1;
}
// Case 2: ans = 2 if the number is a sum of
// two perfect square
// we check for each i if n - (i * i) is a perfect
// square
for (let i = 1; i * i <= n; i++) {
if (isSquare(n - (i * i))) {
return 2;
}
}
// Case 4: ans = 4 if the number is a sum of
// four perfect square
// possible if the number is representable in the form
// 4^a (8*b + 7).
while (n > 0 && n % 4 === 0) {
n /= 4;
}
if (n % 8 === 7) {
return 4;
}
// since all the other cases have been evaluated,
// the answer can only then be 3 if the program
// reaches here
return 3;
}
let n = 6;
console.log(minSquares(n));
Time Complexity: O(sqrt(n))
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem