在 C++ 中查詢能被 3 整除但不能被 6 整除的 n 的排列
假設我們有一個數字 n,我們必須找到這個數字的排列,該排列可以被 3 整除,但不能被 6 整除。如果無法生成這樣的值,則返回 -1。例如,如果 n 是 336,則輸出可以是 363。
眾所周知,一個數字能被 6 整除意味著它能被 3 和 2 整除。因此,每個能被 3 整除的偶數都能被 6 整除。如果我們交換一個能被 3 整除且為偶數的數字的數字,使其變成奇數,它將是結果。
示例
#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); }
輸出
The permutation of 132 that is divisible by 3 but not by 6 is:213
廣告