
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Permutation of N Divisible by 3 but Not by 6 in C++
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
#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
Advertisements