ตรวจสอบเลขใหญ่ (string) หาร 2, 3, 5 ลงตัวพร้อมกันหรือไม่
กฎ: หาร 2,3,5 ลงตัว ⇔ หาร LCM(2,3,5)=30 ลงตัว
⇔ หาร 10 ลงตัว (หลักสุดท้าย 0) และ หาร 3 ลงตัว (ผลรวมหลักเลขหาร 3 ลงตัว)
ตัวอย่างโค้ด
#include <bits/stdc++.h>
using namespace std;
bool isDiv30(string num) {
int n = num.length();
if (num[n-1] != '0') return false;
long sum = accumulate(begin(num), end(num), 0) - '0' * n;
return (sum % 3 == 0);
}
int main() {
string num = "353730746028908374890";
if (isDiv30(num)) cout << "Divisible";
else cout << "Not Divisible";
}
ผลลัพธ์
Divisible