为了找到不是特定数字'k'的幂的前n个自然数的总和,代码如下-
<?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 fist 20 natural numbers that are not powers of 3 is "); echo sum_of_nums($n_val, $k_val); ?>
输出结果
The sum of fist 20 natural numbers that are not powers of 3 is 198
定义了一个名为“ sum_of_nums”的函数,该函数计算不是一定值幂的自然数之和。数字和非幂数字将作为参数传递给此函数。在函数外部,分别定义n和k的值,并在这些值上调用函数。相关输出将显示在控制台上。