📜  用 2 的 N+1 次方表示 2^N

📅  最后修改于: 2022-05-13 01:56:07.168000             🧑  作者: Mango

用 2 的 N+1 次方表示 2^N

给定一个正整数N ,任务是将2^N表示为2的幂和 正好是N+1项。打印那些N+1项。

例子:

方法:我们知道:

因此,在2的一系列幂的开头添加1将导致2^N正好N+1项。

下面是上述方法的实现

C++
// C++ program for the above approach
 
#include 
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


输出
1 1 2 4 8 16 

时间复杂度: O(N)
辅助空间: O(1)