# Count rotations divisible by 4 in C++

We are given a large number. The goal is to count the rotations of num that are divisible by 4.

As the rotations can not be done again and again. We will use the divisible by 4 property. If the last two digits are divisible by 4 then the number is divisible by 4. If the number is 1234 then it’s rotations will be 1234, 4123, 3412, 2341 out of which 3412 will be divisible by 4 as the last two digits 12 is divisible by 4.

Let us understand with examples.

Input − num=15324

Output − Count of rotations divisible by 4 are: 2

Explanation − Rotations are −

15324, 41532, 24153, 32415, 53241

Out of these, 15324 and 41532 will be divisible by 4.

Input − num=848484

Output − Count of rotations divisible by 4 are − 6

Explanation − Rotations are −

848484, 484848, 848484, 484848, 848484, 484848

All these rotations are divisible by 4

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

We will convert the number into a string and traverse the number using a for a loop. For each pair of two digits convert them into an integer and check divisibility by 4. If divisible then increment the count.

• Take the number as long long num.

• Function Rotation_4(long long num) takes the number num and returns the count of rotations of num that are divisible by 4.

• Convert the num to string str=to_string(num).

• The number of digits in num will be length=str.length().

• Take temporary variable digit=0 for storing integer values of pairs of digits.

• Take the initial count as 0.

• If length is 1 then only a single digit is present. Convert it to integer, digit=(str.at(0)-’0’)

• Check divisibility by 4 and return the result as 1 or 0.

• Now traverse str using for loop from i=0 to I <length-1.

• Make two digit number using digit=(str.at(i)-'0')*10 + (str.at(i+1)-'0') as each pair will become the last two digits in rotations.

• Do same process as above for pair formed by last digit and first digit using digit=(str.at(length-1)-'0')*10 + (str.at(0)-'0'); Check divisibility by 4 and update count.

• In the end return count as result.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int Rotation_4(long long num){
string str = to_string(num);
int length = str.length();
int digit = 0, count = 0;
if (length == 1){
digit=(str.at(0)-'0');
if(digit%4 == 0){
return 1;
}
else{
return 0;
}
}
for (int i=0; i<(length-1); i++){
digit = (str.at(i)-'0')*10 + (str.at(i+1)-'0');
if(digit%4 == 0){
count++;
}
}
digit = (str.at(length-1)-'0')*10 + (str.at(0)-'0');
if(digit%4 == 0){
count++;
}
return count;
}
int main(){
long long num = 24040;
cout<<"Count of rotations divisible by 4 are: "<<Rotation_4(num);
return 0;
}

## Output

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

Count of rotations divisible by 4 are: 4