Minimum steps to reduce N to 0 by given operations
Last Updated :
15 Jul, 2025
Give an integer N, the task is to find the minimum number of moves to reduce N to 0 by one of the following operations:
- Reduce N by 1.
- Reduce N to (N/2), if N is divisible by 2.
- Reduce N to (N/3), if N is divisible by 3.
Examples:
Input: N = 10
Output: 4
Explanation:
Here N = 10
Step 1: Reducing N by 1 i.e., 10 - 1 = 9.
Step 2: Since 9 is divisible by 3, reduce it to N/3 = 9/3 = 3
Step 3: Since again 3 is divisible by 3 again repeating step 2, i.e., 3/3 = 1.
Step 4: 1 can be reduced by the step 1, i.e., 1-1 = 0
Hence, 4 steps are needed to reduce N to 0.
Input: N = 6
Output: 3
Explanation:
Here N = 6
Step 1: Since 6 is divisible by 2, then 6/2 =3
Step 2: since 3 is divisible by 3, then 3/3 = 1.
Step 3: Reduce N to N-1 by 1, 1-1 = 0.
Hence, 3 steps are needed to reduce N to 0.
Naive Approach: The idea is to use recursion for all the possible moves. Below are the steps:
- Observe that base case for the problem, if N < 2 then for all the cases the answer will be N itself.
- At every value of N, choose between 2 possible cases:
- Reduce n till n % 2 == 0 and then update n /= 2 with count = 1 + n%2 + f(n/2)
- Reduce n till n % 3 == 0 and then update n /= 3 with count = 1 + n%3 + f(n/3)
- Both the computation results in the recurrence relation as:
count = 1 + min(n%2 + f(n/2), n%3 + f(n/3))
where, f(n) is the minimum of moves to reduce N to 0.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the minimum
// number to steps to reduce N to 0
int minDays(int n)
{
// Base case
if (n < 1)
return n;
// Recursive call to count the
// minimum steps needed
int cnt = 1 + min(n % 2 + minDays(n / 2),
n % 3 + minDays(n / 3));
// Return the answer
return cnt;
}
// Driver Code
int main()
{
// Given number N
int N = 6;
// Function call
cout << minDays(N);
return 0;
}
// This code is contributed by 29AjayKumar
Java
// Java program for the above approach
class GFG{
// Function to find the minimum
// number to steps to reduce N to 0
static int minDays(int n)
{
// Base case
if (n < 1)
return n;
// Recursive Call to count the
// minimum steps needed
int cnt = 1 + Math.min(n % 2 + minDays(n / 2),
n % 3 + minDays(n / 3));
// Return the answer
return cnt;
}
// Driver Code
public static void main(String[] args)
{
// Given Number N
int N = 6;
// Function Call
System.out.print(minDays(N));
}
}
// This code is contributed by PrinciRaj1992
Python3
# Python3 program for the above approach
# Function to find the minimum
# number to steps to reduce N to 0
def minDays(n):
# Base case
if n < 1:
return n
# Recursive Call to count the
# minimum steps needed
cnt = 1 + min(n % 2 + minDays(n // 2),
n % 3 + minDays(n // 3))
# Return the answer
return cnt
# Driver Code
# Given Number N
N = 6
# Function Call
print(str(minDays(N)))
C#
// C# program for the above approach
using System;
class GFG{
// Function to find the minimum
// number to steps to reduce N to 0
static int minDays(int n)
{
// Base case
if (n < 1)
return n;
// Recursive call to count the
// minimum steps needed
int cnt = 1 + Math.Min(n % 2 + minDays(n / 2),
n % 3 + minDays(n / 3));
// Return the answer
return cnt;
}
// Driver Code
public static void Main(String[] args)
{
// Given number N
int N = 6;
// Function call
Console.Write(minDays(N));
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// JavaScript program for the above approach
// Function to find the minimum
// number to steps to reduce N to 0
function minDays(n)
{
// Base case
if (n < 1)
return n;
// Recursive call to count the
// minimum steps needed
var cnt = 1 + Math.min(n % 2 + minDays(parseInt(n / 2)),
n % 3 + minDays(parseInt(n / 3)));
// Return the answer
return cnt;
}
// Driver Code
// Given number N
var N = 6;
// Function call
document.write( minDays(N));
</script>
Time Complexity: O(2N)
Auxiliary Space: O(1)
Efficient Approach: The idea is to use Dynamic Programming. The above recursive approach results in TLE because of the number of repeated subproblems. To optimize the above method using a dictionary to keep track of values whose recursive call is already performed to reduce the further computation such that value can be accessed faster.
Below is the implementation of the above approach:
C++
// C++ program for
// the above approach
#include<bits/stdc++.h>
using namespace std;
// Function to find the minimum
// number to steps to reduce N to 0
int count(int n)
{
// Dictionary for storing
// the precomputed sum
map<int, int> dp;
// Bases Cases
dp[0] = 0;
dp[1] = 1;
// Check if n is not in dp then
// only call the function so as
// to reduce no of recursive calls
if ((dp.find(n) == dp.end()))
dp[n] = 1 + min(n % 2 +
count(n / 2), n % 3 +
count(n / 3));
// Return the answer
return dp[n];
}
// Driver Code
int main()
{
// Given number N
int N = 6;
// Function call
cout << count(N);
}
// This code is contributed by gauravrajput1
Java
// Java program for the above approach
import java.util.HashMap;
class GFG{
// Function to find the minimum
// number to steps to reduce N to 0
static int count(int n)
{
// Dictionary for storing
// the precomputed sum
HashMap<Integer,
Integer> dp = new HashMap<Integer,
Integer>();
// Bases Cases
dp.put(0, 0);
dp.put(1, 1);
// Check if n is not in dp then
// only call the function so as
// to reduce no of recursive calls
if (!dp.containsKey(n))
dp.put(n, 1 + Math.min(n % 2 +
count(n / 2), n % 3 +
count(n / 3)));
// Return the answer
return dp.get(n);
}
// Driver Code
public static void main(String[] args)
{
// Given number N
int N = 6;
// Function call
System.out.println(String.valueOf((count(N))));
}
}
// This code is contributed by Amit Katiyar
Python3
# Python3 program for the above approach
# Function to find the minimum
# number to steps to reduce N to 0
def count(n):
# Dictionary for storing
# the precomputed sum
dp = dict()
# Bases Cases
dp[0] = 0
dp[1] = 1
# Check if n is not in dp then
# only call the function so as
# to reduce no of recursive calls
if n not in dp:
dp[n] = 1 + min(n % 2 + count(n//2), n % 3 + count(n//3))
# Return the answer
return dp[n]
# Driver Code
# Given Number N
N = 6
# Function Call
print(str(count(N)))
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
public class GFG{
// Function to find the minimum
// number to steps to reduce N to 0
static int count(int n)
{
// Dictionary for storing
// the precomputed sum
Dictionary<int,
int> dp = new Dictionary<int,
int>();
// Bases Cases
dp.Add(0, 0);
dp.Add(1, 1);
// Check if n is not in dp then
// only call the function so as
// to reduce no of recursive calls
if (!dp.ContainsKey(n))
dp.Add(n, 1 + Math.Min(n % 2 + count(n / 2),
n % 3 + count(n / 3)));
// Return the answer
return dp[n];
}
// Driver Code
public static void Main(String[] args)
{
// Given number N
int N = 6;
// Function call
Console.WriteLine(String.Join("",
(count(N))));
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// JavaScript program for
// the above approach
// Function to find the minimum
// number to steps to reduce N to 0
function count(n)
{
// Dictionary for storing
// the precomputed sum
var dp = new Map();
// Bases Cases
dp.set(0, 0);
dp.set(1, 1);
// Check if n is not in dp then
// only call the function so as
// to reduce no of recursive calls
if (!dp.has(n))
dp.set(n, 1 + Math.min(n % 2 +
count(parseInt(n / 2)), n % 3 +
count(parseInt(n / 3))));
// Return the answer
return dp.get(n);
}
// Driver Code
// Given number N
var N = 6;
// Function call
document.write( count(N));
</script>
Time Complexity: O(Nlog N), where N represents the given integer.
Auxiliary Space: O(N), where N represents the given integer.
Efficient approach: Using DP Tabulation method
This method Provided further improves on this by avoiding the use of a map and instead using an array to store the previously computed results. This is more efficient as array access is faster than map access.
Implementation steps :
- Create a vector dp of size n+1 and initialize dp[0] to 0 and dp[1] to 1.
- Loop from i=2 to i=n and for each i, compute the minimum number of steps to reduce i to 0 using the recurrence relation dp[i] = 1 + min(dp[i-1], dp[i/2] (if i is even), dp[i/3] (if i is divisible by 3)).
- Return dp[n] as the result.
Implementation:
C++
// C++ program for above approach
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 1e6+5;
int dp[MAXN];
int count(int n)
{
// Base Cases
if(n == 0)
return 0;
if(n == 1)
return 1;
// Check if n is already computed
if(dp[n] != 0)
return dp[n];
// Compute the answer recursively
int ans = 1 + min(n % 2 + count(n / 2), n % 3 + count(n / 3));
// Store the computed answer
dp[n] = ans;
// Return the answer
return ans;
}
int main()
{
// Given number N
int N = 6;
// Initialize the dp array to 0
memset(dp, 0, sizeof(dp));
// Function call
cout << count(N);
}
// this code is contributed by bhardwajji
Java
// Java program for above approach
import java.util.*;
class Main {
static int[] dp = new int[(int)1e6 + 5];
public static int count(int n)
{
// Base Cases
if (n == 0)
return 0;
if (n == 1)
return 1;
// Check if n is already computed
if (dp[n] != 0)
return dp[n];
// Compute the answer recursively
int ans = 1
+ Math.min(n % 2 + count(n / 2),
n % 3 + count(n / 3));
// Store the computed answer
dp[n] = ans;
// Return the answer
return ans;
}
public static void main(String[] args)
{
// Given number N
int N = 6;
// Initialize the dp array to 0
Arrays.fill(dp, 0);
// Function call
System.out.println(count(N));
}
}
// This code is contributed by sarojmcy2e
Python3
MAXN = 1000005
dp = [0] * MAXN
def count(n):
# Base Cases
if n == 0:
return 0
if n == 1:
return 1
# Check if n is already computed
if dp[n] != 0:
return dp[n]
# Compute the answer recursively
ans = 1 + min(n % 2 + count(n // 2), n % 3 + count(n // 3))
# Store the computed answer
dp[n] = ans
# Return the answer
return ans
# Given number N
N = 6
# Initialize the dp array to 0
dp = [0] * MAXN
# Function call
print(count(N))
C#
using System;
class MainClass {
const int MAXN = 1000005;
static int[] dp = new int[MAXN];
static int count(int n) {
// Base Cases
if (n == 0)
return 0;
if (n == 1)
return 1;
// Check if n is already computed
if (dp[n] != 0)
return dp[n];
// Compute the answer recursively
int ans = 1 + Math.Min(n % 2 + count(n / 2), n % 3 + count(n / 3));
// Store the computed answer
dp[n] = ans;
// Return the answer
return ans;
}
public static void Main() {
// Given number N
int N = 6;
// Initialize the dp array to 0
Array.Fill(dp, 0);
// Function call
Console.WriteLine(count(N));
}
}
JavaScript
// Javascript program for above approach
let dp = new Array(1000005).fill(0);
function count(n) {
// Base Cases
if (n == 0)
return 0;
if (n == 1)
return 1;
// Check if n is already computed
if (dp[n] != 0)
return dp[n];
// Compute the answer recursively
let ans = 1 + Math.min(n % 2 + count(Math.floor(n / 2)),
n % 3 + count(Math.floor(n / 3)));
// Store the computed answer
dp[n] = ans;
// Return the answer
return ans;
}
// Given number N
let N = 6;
// Function call
console.log(count(N));
Time Complexity: O(N)
Auxiliary Space: O(N),
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