Given a number N ( maybe up to 10^9 ). The task is to find the sum of first N natural number taking powers of 2 as a negative number.
Input: N = 4 Output: -4 - 1 - 2 + 3 - 4 = -4 1, 2, and 4 are the powers of two. Input: N = 5 Output: 1
Approach: An efficient solution is to store the powers of two in an array and then store presum of this array in another array. This array size can be at most 30. So, normally search for the first element in the power array which is greater than the given number.
Below is the implementation of above approach:
$ans -= 2 * $pre[$i – 1];
// Driver code
// function call
$n = 4;
// function call
// This code is contributed by mits
- 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
- Find if given number is sum of first n natural numbers
- Number of pairs from the first N natural numbers whose sum is divisible by K
- Number of distinct prime factors of first n natural numbers
- Count pairs of natural numbers with GCD equal to given number
- Find the number of sub arrays in the permutation of first N natural numbers such that their median is M
- 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
- Count numbers in a range having GCD of powers of prime factors equal to 1
- Minimum number of given powers of 2 required to represent a number
- Representation of a number in powers of other
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.