Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

PHP ผลรวมกำลังสองของ N จำนวนธรรมชาติแรก

ตัวอย่างโค้ด

<?php
function sum_of_squares($limit) {
    $ini_sum = 0;
    for ($i = 1; $i <= $limit; $i++) {
        $ini_sum += ($i * $i);  // Fixed: ใช้ $i ไม่ใช่ $limit
    }
    return $ini_sum;
}

$limit = 5;
echo "The sum of square of first 5 natural numbers is " . sum_of_squares($limit);
?>

ผลลัพธ์

The sum of square of first 5 natural numbers is 55

คำอธิบาย

หมายเหตุ: โค้ดต้นฉบับมี Bug: $ini_sum += ($limit * $limit) ควรเป็น $ini_sum += ($i * $i)

Formula: 1² + 2² + 3² + 4² + 5² = 1 + 4 + 9 + 16 + 25 = 55

Mathematical Formula (O(1))

ผลรวมกำลังสอง N จำนวนแรก = n(n+1)(2n+1)/6

<?php
function sum_of_squares_formula($n) {
    return $n * ($n + 1) * (2 * $n + 1) / 6;
}

echo sum_of_squares_formula(5);  // 55
echo sum_of_squares_formula(100); // 338350 (Instant)
?>

การเปรียบเทียบ Performance

  • Loop O(n) - ช้าเมื่อ N ใหญ่
  • Formula O(1) - คงที่ ไม่ว่าจะ N ใหญ่แค่ไหน
  • ควรใช้ Formula สำหรับ Production Code