Calculate sum of all integers from 1 to N , excluding perfect power of 2 | Java implementation of the above approach ; Function to find the required summation ; Find the sum of first N integers using the formula ; Find the sum of numbers which are exact power of 2 by using the formula ; Print the final Sum ; Driver Code ; Function to find the sum
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 ) ; } }