ตัวอย่างโค้ด
<?php
function sum_of_cubes($val) {
$init_sum = 0;
for ($x = 1; $x <= $val; $x++) {
$init_sum += $x * $x * $x;
}
return $init_sum;
}
echo "The sum of cubes of first 8 natural numbers is " . sum_of_cubes(8);
?>
ผลลัพธ์
The sum of cubes of first 8 natural numbers is 1296
คำอธิบาย
1³ + 2³ + 3³ + 4³ + 5³ + 6³ + 7³ + 8³ = 1 + 8 + 27 + 64 + 125 + 216 + 343 + 512 = 1296
Mathematical Formula (O(1))
ผลรวมกำลังสาม N จำนวนแรก = [n(n+1)/2]² (Square ของ Triangular Number)
<?php
function sum_of_cubes_formula($n) {
$triangular = $n * ($n + 1) / 2;
return $triangular * $triangular;
}
echo sum_of_cubes_formula(8); // 1296
echo sum_of_cubes_formula(100); // 25502500 (Instant)
?>
ความสนใจ
ผลรวมกำลังสาม = (ผลรวมจำนวนธรรมชาติ)²
1³ + 2³ + ... + n³ = (1 + 2 + ... + n)²