# Count operations of the given type required to reduce N to 0 in C++

We are given a positive integer N. The goal is to find the number of operations required to reduce N to 0. Operation applied is N=N-P where P is the smallest prime divisor of P.

Let us understand with examples

Input − N=17

Output − Count of operations of the given type required to reduce N to 0 are − 1

Explanation − The smallest prime divisor of 17 is 17 itself. So the operation is applied only once 17-17=0.

Input − N=20

Output− Count of operations of the given type required to reduce N to 0 are − 10

Explanation − The smallest prime divisor of 20 is 2. Subtracting 2 again and again and finding next prime divisor:

20%2==0, 20-2=18
18%2==0, 18-2=16
…………………..14, 12, 10, 8, 6, 4, 2, 0 Total 10 times the operation is applied.

## The approach used in the below program is as follows

For all even N’s the smallest prime divisor will always be 2 and subtracting 2 from even N will again produce an even number. For all odd numbers the smallest prime divisor will be odd, after subtracting odd from odd and number will become even so again 2 will become the smallest prime divisor. To find smallest prime divisor start from i=2 to i such that i*i<N and N%i==0. Total operations then would be count=1 + (N-i)/2.

• Take an integer N as input.

• Function N_to_Zero(int N) takes N and returns the number of operations required to reduce N to 0.

• Take the initial value of count as 0.

• Starting from i=2. Start traversing while (i*i)<N and N is not divisible by i (N%i!=0). Increment i.

• If (i*i) exceeds N, set i=N.

• The number of operations will be 1+(N-i)/2.

• Set count as 1+(N-i)/2.

• Return count as result.

## Example

Live Demo

#include<bits/stdc++.h>
using namespace std;
int N_to_Zero(int N){
int count = 0;
int i = 2;
while((i * i) < N && (N % i)){
i++;
}
if((i * i) > N){
i = N;
}
count = 1 + (N-i)/2;
return count;
}
int main(){
int N = 10;
cout<<"Count of operations of the given type required to reduce N to 0 are: "<<N_to_Zero(N);
return 0;
}

## Output

If we run the above code it will generate the following output −

Count of operations of the given type required to reduce N to 0 are: 5