Calculate sum of all integers from 1 to N, excluding perfect power of 2
Last Updated :
05 Nov, 2021
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.
Examples:
Input: N = 2
Output: 0
Input: N = 1000000000
Output: 499999998352516354
Naive Approach:
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)
Efficient Approach:
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:
C++
#include <bits/stdc++.h>
using namespace std;
void findSum( int N)
{
int sum = (N) * (N + 1) / 2;
int r = log2(N) + 1;
int expSum = pow (2, r) - 1;
cout << sum - expSum << endl;
}
int main()
{
int N = 2;
findSum(N);
return 0;
}
|
Java
import java.lang.Math;
class GFG{
public static void findSum( int N)
{
int sum = (N) * (N + 1 ) / 2 ;
int r = ( int )(Math.log(N) /
Math.log( 2 )) + 1 ;
int expSum = ( int )(Math.pow( 2 , r)) - 1 ;
System.out.println(sum - expSum);
}
public static void main(String[] args)
{
int N = 2 ;
findSum(N);
}
}
|
Python3
from math import log2, pow
def findSum(N):
sum = (N) * (N + 1 ) / / 2
r = log2(N) + 1
expSum = pow ( 2 , r) - 1
print ( int ( sum - expSum))
if __name__ = = '__main__' :
N = 2
findSum(N)
|
C#
using System;
class GFG{
public static void findSum( int N)
{
int sum = (N) * (N + 1) / 2;
int r = ( int )(Math.Log(N) /
Math.Log(2)) + 1;
int expSum = ( int )(Math.Pow(2, r)) - 1;
Console.Write(sum - expSum);
}
public static void Main( string [] args)
{
int N = 2;
findSum(N);
}
}
|
Javascript
<script>
function findSum(N)
{
var sum = (N) * (N + 1) / 2;
var r = (Math.log(N) /
Math.log(2)) + 1;
var expSum = (Math.pow(2, r)) - 1;
document.write(sum - expSum);
}
var N = 2;
findSum(N);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...