Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> PHP

Chương trình PHP tính tổng lập phương n số tự nhiên đầu tiên

Ví dụ

<?php
function sum_of_cubes($val) {
    $init_sum = 0;
    for ($x = 1; $x <= $val; $x++)
        $init_sum += $x * $x * $x;
    return $init_sum;
}
print_r("The sum of cubes of first 8 natural numbers is ");
echo sum_of_cubes(8);
?>

Kết quả

The sum of cubes of first 8 natural numbers is 1296

Giải thích

Hàm sum_of_cubes khởi tạo sum=0. Mỗi số tự nhiên nhân chính nó 3 lần (lập phương) cộng vào sum. Gọi hàm với limit=8: 1³+2³+...+8³ = 1296. Công thức toán học: (n(n+1)/2)² = (8*9/2)² = 36² = 1296.