Given an integer n. The task is to count the number of operations required to reduce n to 0. In every operation, n can be updated as n = n – d where d is the smallest prime divisor of n.
Input: n = 5
5 is the smallest prime divisor, thus it gets subtracted and n gets reduced to 0.
Input: n = 25
5 is the smallest prime divisor, thus it gets subtracted and n gets reduced to 20. Then 2 is the smallest divisor and so on.
Input: n = 4
- When n is even then the smallest prime divisor of n will be 2 and subtracting 2 from n will again give an even integer i.e. gain 2 will be chosen as the smallest prime divisor and these steps will repeat until n gets reduced to 0.
- When n is odd then the smallest prime divisor of n will also be odd and subtracting an odd integer from another odd integer will give an even integer as the result and then the result can be found out by repeating step 1 for the current even integer.
- Thus, the task is to find the smallest divisor d, subtract it, n = n – d and print 1 + ((n – d) / 2).
Below is the implementation of the above approach:
// Java implementation of the approach
// Function to return the required
// number of operations
static int countOperations (int n)
int i = 2;
// Finding the smallest divisor
while ((i * i) < n && (n % i) > 0)
i += 1;
if ((i * i) > n)
i = n;
// Return the count of operations
return (1 + (n – i) / 2);
// Driver code
public static void main(String args)
int n = 5;
// This code is contributed
// by Akanksha Rai
- Minimum number of operations required to reduce N to 1
- Minimum operations of the given type required to make a complete graph
- Count the number of carry operations required to add two numbers
- Find maximum operations to reduce N to 1
- Minimum operations required to make all the elements distinct in an array
- Minimum operations required to make all the array elements equal
- Minimum number of operations required to delete all elements of the array
- Program to find the count of coins of each type from the given ratio
- Maximum count of equal numbers in an array after performing given operations
- Reduce the array to a single element with the given operation
- Steps to reduce N to zero by subtracting its most significant digit at every step
- Maximizing Probability of one type from N containers
- Powers of 2 to required sum
- Minimum Players required to win the game
- Operations on Sparse Matrices