Sum of first N natural numbers with all powers of 2 added twice | C ++ program to implement the above approach ; Function to raise N to the power P and return the value ; Function to calculate the log base 2 of an integer ; Calculate log2 ( N ) indirectly using log ( ) method ; Function to calculate and return the required sum ; Sum of first N natural numbers ; Sum of all powers of 2 up to N ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; double power ( int N , int P ) { return pow ( N , P ) ; } int Log2 ( int N ) { int result = ( int ) ( log ( N ) / log ( 2 ) ) ; return result ; } double specialSum ( int n ) { double sum = n * ( n + 1 ) / 2 ; int a = Log2 ( n ) ; sum = sum + power ( 2 , a + 1 ) - 1 ; return sum ; } int main ( ) { int n = 4 ; cout << ( specialSum ( n ) ) << endl ; return 0 ; }