ให้ตัวเลข n ตรวจสอบว่าทุกหลักของ n หาร n ลงตัวหรือไม่ เช่น 'xy' ต้องมี x หาร n ลงตัว และ y หาร n ลงตัว
ตัวอย่าง
Input - 24 Output - Yes
คำอธิบาย - 24 % 2 == 0, 24 % 4 == 0
ใช้ Conditional Statement ตรวจสอบแต่ละหลัก ว่าต่างจาก 0 และหาร n ลงตัว วนลูปแยกหลักทีละหลัก
ตัวอย่าง
#include <stdio.h>
int main() {
int n = 24;
int temp = n;
int flag = 1;
while (temp > 0) {
int r = n % 10;
if (!(r != 0 && n % r == 0)) {
flag = 0;
}
temp /= 10;
}
if (flag == 1)
printf("The number is divisible by its digits");
else
printf("The number is not divisible by its digits");
return 0;
}ผลลัพธ์
The number is divisible by its digits