Sum of first N natural numbers with all powers of 2 added twice | Java 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
import java . util . * ; import java . lang . Math ; class GFG { static double power ( int N , int P ) { return Math . pow ( N , P ) ; } public static int log2 ( int N ) { int result = ( int ) ( Math . log ( N ) / Math . log ( 2 ) ) ; return result ; } static double specialSum ( int n ) { double sum = n * ( n + 1 ) / 2 ; int a = log2 ( n ) ; sum = sum + power ( 2 , a + 1 ) - 1 ; return sum ; } public static void main ( String [ ] args ) { int n = 4 ; System . out . println ( specialSum ( n ) ) ; } }