สมมติว่ามีตัวเลข 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