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

PHP ผลรวม N จำนวนแรกที่ไม่ใช่กำลังของ K

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

<?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;
echo "The sum of first 20 natural numbers that are not powers of 3 is " . sum_of_nums($n_val, $k_val);
?>

ผลลัพธ์

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

คำอธิบาย

  1. คำนวณ Sum ทั้งหมด 1 ถึง N: N(N+1)/2 = 20×21/2 = 210
  2. ลบ Powers of K ที่ ≤ N: 3¹=3, 3²=9, 3³=27(>20 stop)
  3. 210 - 3 - 9 = 198

ตรวจสอบ

Powers of 3 ≤ 20: 3, 9

Numbers 1..20 except 3,9: 1,2,4,5,6,7,8,10,11,12,13,14,15,16,17,18,19,20

Sum = 210 - 12 = 198 ✓

Edge Cases

  • K = 1: Powers = 1,1,1,... Infinite Loop! ต้อง Handle แยก
  • K = 0: 0¹=0, 0²=0,... ต้อง Handle
  • K < 0: Alternating Signs

Fixed Version

<?php
function sum_not_powers_of_k($n, $k) {
    if ($k <= 1) return ($n * ($n + 1)) / 2;  // K=0,1: All or None
    if ($k < 0) {
        // Handle negative K if needed
        return "Negative K not supported";
    }
    
    $total = $n * ($n + 1) / 2;
    $power = $k;
    while ($power <= $n) {
        $total -= $power;
        $power *= $k;
    }
    return $total;
}

echo sum_not_powers_of_k(20, 3);  // 198
echo sum_not_powers_of_k(100, 2); // 5050 - (2+4+8+16+32+64) = 5050-126 = 4924
?>