Sum of first N natural numbers with all powers of 2 added twice | Python3 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 math NEW_LINE def power ( N , P ) : NEW_LINE INDENT return math . pow ( N , P ) NEW_LINE DEDENT def Log2 ( N ) : NEW_LINE INDENT result = ( math . log ( N ) // math . log ( 2 ) ) NEW_LINE return result NEW_LINE DEDENT def specialSum ( n ) : NEW_LINE INDENT sum = n * ( n + 1 ) // 2 NEW_LINE a = Log2 ( n ) NEW_LINE sum = sum + power ( 2 , a + 1 ) - 1 NEW_LINE return sum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE print ( specialSum ( n ) ) NEW_LINE DEDENT