Given a positive integer N, the task is to calculate the sum of all integers from 1 to N but excluding the number which is a perfect power of 2.
Input: N = 2
Input: N = 1000000000
The naive approach is to iterate every number from 1 to N and compute the sum in the variable by excluding the number which is a perfect power of 2. But to compute the sum to the number 10^9, the above approach will give Time Limit Error.
Time Complexity: O(N)
To find desired sum, below are the steps:
- Find the sum of all the number till N using the formula discussed in this article in O(1) time.
- Since sum of all perfect power of 2 forms a Geometric Progression. Hence the sum of all powers of 2 less than N is calculated by the below formula:
The number of element with perfect power of 2 less than N is given by log2N,
Let r = log2N
And the sum of all numbers which are perfect power of 2 is given by 2r – 1.
- Subtract the sum of all perfect powers of 2 calculated above from the sum of first N numbers to get the result.
Below is the implementation of the above approach:
Time Complexity: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.