ตัวอย่างโค้ด
<?php
function sum_of_fifth_pow($val) {
$init_sum = 0;
for ($i = 1; $i <= $val; $i++) {
$init_sum += $i * $i * $i * $i * $i;
}
return $init_sum;
}
$val = 89;
echo "The sum of fifth powers of the first n natural numbers is " . sum_of_fifth_pow($val);
?>
ผลลัพธ์
The sum of fifth powers of the first n natural numbers is 85648386825
Mathematical Formula (Faulhaber's Formula)
ผลรวมกำลังห้า: n²(n+1)²(2n²+2n-1)/12
<?php
function sum_fifth_powers_formula($n) {
$n2 = $n * $n;
$n1_2 = ($n + 1) * ($n + 1);
return $n2 * $n1_2 * (2 * $n2 + 2 * $n - 1) / 12;
}
echo sum_fifth_powers_formula(89); // 85648386825 (Instant vs Loop)
?>
General Power Sum Formulas
| Power | Formula |
|---|---|
| 1 | n(n+1)/2 |
| 2 | n(n+1)(2n+1)/6 |
| 3 | [n(n+1)/2]² |
| 4 | n(n+1)(2n+1)(3n²+3n-1)/30 |
| 5 | n²(n+1)²(2n²+2n-1)/12 |
Bernoulli Numbers
General Formula ใช้ Bernoulli Numbers: ∑kᵖ = 1/(p+1) ∑(j=0 to p) C(p+1,j) Bⱼ n^(p+1-j)