用 2 的 N+1 次方表示 2^N
给定一个正整数N ,任务是将2^N表示为2的幂和 正好是N+1项。打印那些N+1项。
例子:
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 + 8
Input: N = 5
Output: 1 1 2 4 8 16
方法:我们知道:
2^0 + 2^1 +…. 2^(N-1) = 2^N -1
因此,在2的一系列幂的开头添加1将导致2^N正好N+1项。
1 + 2^0 + 2^1 +…. 2^(N-1) = 2^N
下面是上述方法的实现
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)