# Find permutation of n which is divisible by 3 but not divisible by 6 in C++

C++Server Side ProgrammingProgramming

Suppose we have a number n, and we have to find the permutation of this number, that is divisible by 3, but not divisible by 6. If no such value can be made, then return -1. For example, if n is 336, then the output can be 363.

As we know a number is divisible by 6 means it is divisible by 3 and 2. So each even number that is divisible by 3, will be divisible by 6. If we interchange the digits of a number which is divisible by 3 and also even, to make it odd, it will be the result.

## Example

Live Demo

#include<iostream>
#include<cmath>
using namespace std;
int findNumber(int n) {
int digit_count = ceil(log10(n));
for (int i = 0; i < digit_count; i++) {
if (n % 2 != 0) {
return n;
} else {
n = (n / 10) + (n % 10) * pow(10, digit_count - i - 1);
continue;
}
}
return -1;
}
int main() {
int n = 132;
cout <<"The permutation of "<<n << " that is divisible by 3 but not by 6 is:"<< findNumber(n);
}

## Output

The permutation of 132 that is divisible by 3 but not by 6 is:213
Published on 18-Dec-2019 12:53:38