Given a positive integer N, the task is to express 2^N in the sum of powers of 2 and in exactly N+1 terms. Print those N+1 terms.
Example:
Input: N = 4
Output: 1 1 2 4 8
Explanation: 2^4 = 2^0 + 2^0 + 2^1 + 2^2 + 2^3 = 1 + 1 + 2 + 4 + 8Input: N = 5
Output: 1 1 2 4 8 16
Approach: As we know:
2^0 + 2^1 +…. 2^(N-1) = 2^N -1
Therefore, adding 1 at the beginning of the series of powers of 2 will result in 2^N in exactly N+1 terms.
1 + 2^0 + 2^1 +…. 2^(N-1) = 2^N
Below is the implementation of the above approach
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to find exactly N + 1 terms // of powers of 2 series, whose sum is 2^N void powerOf2( long long N) { cout << 1 << ' ' ; for ( int i = 0; i < N; ++i) { cout << ( long long ) pow (2, i) << ' ' ; } } // Driver Code int main() { long long N = 5; powerOf2(N); } |
Java
// Java program for the above approach import java.util.*; public class GFG { // Function to find exactly N + 1 terms // of powers of 2 series, whose sum is 2^N static void powerOf2( long N) { System.out.print( 1 ); for ( int i = 0 ; i < N; ++i) { System.out.print( " " + ( long )Math.pow( 2 , i)); } } // Driver Code public static void main(String args[]) { long N = 5 ; powerOf2(N); } } // This code is contributed by Samim Hossain Mondal |
C#
// C# program for the above approach using System; class GFG { // Function to find exactly N + 1 terms // of powers of 2 series, whose sum is 2^N static void powerOf2( long N) { Console.Write(1); for ( int i = 0; i < N; ++i) { Console.Write( " " + ( long )Math.Pow(2, i)); } } // Driver Code public static void Main() { long N = 5; powerOf2(N); } } // This code is contributed by Samim Hossain Mondal |
Python3
# Python3 program for the above approach import math # Function to find exactly N + 1 terms # of powers of 2 series, whose sum is 2^N def powerOf2(N) : print ( 1 ,end = ' ' ); for i in range (N) : print ( int (math. pow ( 2 , i)),end = ' ' ); # Driver Code if __name__ = = "__main__" : N = 5 ; powerOf2(N); # This code is contributed by AnkThon |
Javascript
<script> // JavaScript program for the above approach // Function to find exactly N + 1 terms // of powers of 2 series, whose sum is 2^N function powerOf2(N) { document.write(1 + ' ' ); for ( var i = 0; i < N; ++i) { document.write(Math.pow(2, i) + ' ' ); } } // Driver Code N = 5; powerOf2(N); // This code is contributed by AnkThon </script> |
1 1 2 4 8 16
Time Complexity: O(N*log(N))
Auxiliary Space: O(1)