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

Chương trình PHP tổng n số tự nhiên đầu không phải lũy thừa của k

Ví dụ

<?php
function sum_of_nums($n_val, $k_val) {
    $tot_sum = ($n_val * ($n_val + 1)) / 2;
    $pow_val = $k_val;
    while ($pow_val <= $n_val) {
        $tot_sum -= $pow_val;
        $pow_val *= $k_val;
    }
    return $tot_sum;
}
$n_val = 20;
$k_val = 3;
print_r("The sum of first 20 natural numbers that are not powers of 3 is ");
echo sum_of_nums($n_val, $k_val);
?>

Kết quả

The sum of first 20 natural numbers that are not powers of 3 is 198

Giải thích

Hàm sum_of_nums tính tổng 1..n trừ đi các lũy thừa của k (k, k², k³... ≤ n). Tổng 1..n = n(n+1)/2 = 210. Lũy thừa của 3 ≤ 20: 3, 9. Trừ đi: 210 - 3 - 9 = 198. (27 > 20 dừng).

Sửa lỗi chính tả: Output gốc ghi "fist" thay vì "first". Đã sửa.