ตรวจสอบเลขใหญ่ (string) หาร 3 ลงตัวหรือไม่
กฎ: ผลรวมหลักเลขหาร 3 ลงตัว → เลขนั้นหาร 3 ลงตัว
ตัวอย่างโค้ด
#include <bits/stdc++.h>
using namespace std;
bool isDiv3(string num) {
int n = num.length();
long sum = accumulate(begin(num), end(num), 0) - '0' * n;
return (sum % 3 == 0);
}
int main() {
string num = "3635883959606670431112222";
if (isDiv3(num)) cout << "Divisible";
else cout << "Not Divisible";
}
ผลลัพธ์
Divisible