Dado un entero positivo N , la tarea es expresar 2^N en la suma de potencias de 2 y exactamente en N+1 términos. Imprime esos términos N+1 .
Ejemplo:
Entrada : N = 4
Salida : 1 1 2 4 8
Explicación : 2^4 = 2^0 + 2^0 + 2^1 + 2^2 + 2^3 = 1 + 1 + 2 + 4 + 8Entrada : N = 5
Salida : 1 1 2 4 8 16
Enfoque: Como sabemos que:
2^0 + 2^1 +…. 2^(N-1) = 2^N-1
Por lo tanto, sumar 1 al principio de la serie de potencias de 2 dará como resultado 2^N exactamente en N+1 términos.
1 + 2^0 + 2^1 +…. 2^(N-1) = 2^N
A continuación se muestra la implementación del enfoque anterior.
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
Complejidad temporal: O(N)
Espacio auxiliar: O(1)
Publicación traducida automáticamente
Artículo escrito por tmprofessor y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA