Input: N = 4
Sum = 2+4+3+8 = 17
Since 1, 2 and 4 are 2 0, 2 1 and 2 2 respectively, they are added twice to the sum.
Input: N = 5
The sum is equal to 2+4+3+8+5 = 22,
because 1, 2 and 4 are 2 0, 2 1 and 2 2 respectively.
The simplest approach to solve this problem is to iterate upto N, and keep calculating the sum by adding every number once except the powers of 2, which needs to be added twice.
Time Complexity: O(N)
Auxiliary Space: O(1)
Follow the steps below to optimize the above approach:
- Calculate sum of first N natural numbers by the formula (N * (N + 1)) / 2.
- Now, all powers of 2 needs to be added once more. Sum of all powers of 2 up to N can be calculated as 2 log2(N) + 1 – 1.
- Hence, the required sum is:
(N * (N + 1)) / 2 + 2 log2(N) + 1 – 1
Below is the implementation of the above approach:
Time Complexity: O(log2(N))
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Sum of kth powers of first n natural numbers
- Sum of fifth powers of the first n natural numbers
- Sum of first N natural numbers which are not powers of K
- Sum of fourth powers of the first n natural numbers
- Sum of fourth powers of first n odd natural numbers
- Sum of first N natural numbers by taking powers of 2 as negative number
- Find k numbers which are powers of 2 and have sum N | Set 1
- Print all integers that are sum of powers of two given numbers
- Find the sum of numbers from 1 to n excluding those which are powers of K
- Minimum numbers with one's place as 9 to be added to get N
- Fill the missing numbers in the array of N natural numbers such that arr[i] not equal to i
- Count of numbers whose sum of increasing powers of digits is equal to the number itself
- Count numbers in a range having GCD of powers of prime factors equal to 1
- Sum of first n natural numbers
- Natural Numbers
- LCM of First n Natural Numbers
- Sum of cubes of first n odd natural numbers
- Sum of all odd natural numbers in range L and R
- Sum of cubes of even and odd natural numbers
- Repeated sum of first N natural numbers
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.