# Possible cuts of a number such that maximum parts are divisible by 3 in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a large integer value (with up to 105 digits). Our task is to print the total number of cuts required such that maximum parts are divisible by 3.

Let’s take an example to understand the problem

Input − 9216

Output − 3

Explanation − the number is divided as 9|21|6.

To solve this problem, we will have to start for the least significant bit of the number i.e. the last digit of the number. For here, we will find the smallest number divisible by three. And then update count based on it.

Example − if arr[i] makes a 3 divisible number, then we will increase the count and move to the next digit of the number. If arr[i] is not divisible by 3, then we will combine it with the next digit and check for divisibility of 3.

Divisibility of 3 − A number is divisible by 3 if the number of digits of the number is divisible by three.

## Example

Program to show the implementation of our solution

Live Demo

#include <bits/stdc++.h>
using namespace std;
int countMaximum3DivisibleNumbers(string number){
int n = number.length();
vector<int> remIndex(3, -1);
remIndex = 0;
vector<int> counter(n + 1);
int r = 0;
for (int i = 1; i <= n; i++) {
r = (r + number[i-1] - '0') % 3;
counter[i] = counter[i-1];
if (remIndex[r] != -1)
counter[i] = max(counter[i], counter[remIndex[r]] + 1);
remIndex[r] = i+1;
}
return counter[n];
}
int main() {
string number = "216873491";
cout<<"The number of 3 divisible number created by cutting "<<number<<" are : " <<countMaximum3DivisibleNumbers(number);
return 0;
}

## Output

The number of 3 divisible number created by cutting 216873491 are : 5