PHP program to find the sum of the first n natural numbers who are not powers of a specific number 'k'

To find the sum of the first n natural numbers that are not powers of a specific number 'k', we calculate the total sum of natural numbers and subtract the powers of k that fall within the range.

Algorithm

The approach involves calculating the sum of all natural numbers from 1 to n using the formula n * (n + 1) / 2, then subtracting all powers of k that are less than or equal to n.

Example

Here's a PHP program that finds the sum of the first n natural numbers excluding powers of 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: ";
echo sum_of_nums($n_val, $k_val);
?>

Output

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

How It Works

The function sum_of_nums performs these steps ?

  • Calculates the sum of all natural numbers from 1 to n using the formula
  • Identifies powers of k within the range (3¹=3, 3²=9, 3³=27 > 20)
  • Subtracts these powers (3 and 9) from the total sum
  • Returns the final result: 210 - 3 - 9 = 198

Conclusion

This efficient approach uses mathematical formulas to calculate the sum without iterating through each number individually. The time complexity is O(log n) based on the number of powers of k within the range.

Updated on: 2026-03-15T09:06:30+05:30

479 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements