Cho n, tìm hoán vị của n chia hết cho 3 nhưng không chia hết cho 6. Nếu không có trả về -1. Ví dụ n=336 → 363.
Số chia hết cho 6 là chia hết cho 2 và 3. Nếu số chia hết cho 3 và chẵn, hoán vị chữ số để thành số lẻ.
Ví dụ
#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); }
Kết quả
The permutation of 132 that is divisible by 3 but not by 6 is:213