การตรวจสอบว่าตัวเลขหารด้วย 3 และ 5 ลงตัว (Divisible by both 3 and 5) ใช้ **Logical AND Operator (&&)** ร่วมกับ **Modulo Operator (%)**
หลักการ
if (num % 3 == 0 && num % 5 == 0) {
// หาร 3 ลงตัว และ หาร 5 ลงตัว
}
num % 3 == 0→ หาร 3 ลงตัว (เศษ 0)num % 5 == 0→ หาร 5 ลงตัว (เศษ 0)&&→ Logical AND (ทั้งสองเงื่อนไขต้อง True)
ตัวอย่างโค้ดสมบูรณ์
using System;
namespace Demo {
class MyApplication {
static void Main(string[] args) {
int num = 15;
Console.WriteLine("Number: " + num);
// ตรวจสอบหาร 3 และ 5 ลงตัว
if (num % 3 == 0 && num % 5 == 0) {
Console.WriteLine("Divisible by 3 and 5");
} else {
Console.WriteLine("Not divisible by 3 and 5");
}
Console.ReadLine();
}
}
}
ผลลัพธ์
Number: 15
Divisible by 3 and 5
ขยาย: พิมพ์ตัวเลขทั้งหมดที่หาร 3 และ 5 ลงตัว (1 ถึง N)
using System;
public class Demo {
public static void Main() {
int limit = 100;
Console.WriteLine($"Numbers divisible by 3 and 5 (1 to {limit}):");
for (int i = 1; i <= limit; i++) {
if (i % 3 == 0 && i % 5 == 0) {
Console.Write(i + " ");
}
}
// Output: 15 30 45 60 75 90
}
}
FizzBuzz Classic Problem
ปัญหา классическое ที่ใช้เงื่อนไขนี้:
for (int i = 1; i <= 100; i++) {
if (i % 15 == 0) // หาร 3 และ 5 ลงตัว = หาร 15 ลงตัว
Console.WriteLine("FizzBuzz");
else if (i % 3 == 0)
Console.WriteLine("Fizz");
else if (i % 5 == 0)
Console.WriteLine("Buzz");
else
Console.WriteLine(i);
}
Optimization: ใช้ LCM (Least Common Multiple)
แทนที่จะเช็ค 2 ครั้ง ใช้ num % 15 == 0 แทน (LCM ของ 3 และ 5 = 15)
// ทั้งสองเทียบเท่ากัน แต่ % 15 เร็วกว่าเล็กน้อย
if (num % 3 == 0 && num % 5 == 0) // 2 Modulo Operations
if (num % 15 == 0) // 1 Modulo Operation
Benchmark
| Method | Operations | Relative Speed |
|---|---|---|
num % 3 == 0 && num % 5 == 0 |
2 Modulo + 1 Branch | Baseline |
num % 15 == 0 |
1 Modulo + 1 Branch | ~2x Faster |
ขยาย: หาตัวเลขหาร 3 หรือ 5 ลงตัว (OR Condition)
if (num % 3 == 0 || num % 5 == 0) {
// หาร 3 ลงตัว หรือ หาร 5 ลงตัว (หรือทั้งคู่)
}
// ผลลัพธ์ 1-20: 3, 5, 6, 9, 10, 12, 15, 18, 20
Best Practices
- ใช้
num % 15 == 0แทน&&สำหรับ Performance และความชัดเจน - Extract เป็น Method:
bool IsDivisibleBy15(int n) => n % 15 == 0; - พิจารณา
Math.DivRemถ้าต้องการทั้งผลหารและเศษพร้อมกัน