- Related Questions & Answers
- PHP program to find the sum of the 5th powers of first n natural numbers
- PHP program to find the sum of first n natural numbers that are divisible by a number ‘x’ or a number ‘y’
- PHP program to find the sum of cubes of the first n natural numbers
- 8085 program to find the sum of first n natural numbers
- PHP program to calculate the sum of square of first n natural numbers
- PHP program to find the average of the first n natural numbers that are even
- Java program to find the sum of n natural numbers
- Program to find sum of first n natural numbers in C++
- PHP program to find the first ‘n’ numbers that are missing in an array
- C Program for the cube sum of first n natural numbers?
- PHP program to find the sum of cubes of natural numbers that are odd
- Sum of first n natural numbers in C Program
- Find k numbers which are powers of 2 and have sum N in C++
- Java Program to cube sum of first n natural numbers
- PHP program to find the first natural number whose factorial can be divided by a number ‘x’

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

To find the sum of the first n natural numbers who are not powers of a specific number ‘k’, the code is as follows −

<?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

A function named ‘sum_of_nums’ is defined and it calculates the sum of natural numbers that are not powers of a certain value. The number and the non-power number are passed as parameters to this function. Outside the function, a value each for n and k is defined and the function is called on these values. Relevant output is displayed on the console.

Advertisements