WAP to print the following series. 1 3 7 15 31... n
Objective
Write a C++ program to print the exponential sum series: 1, 3, 7, 15, 31 ... N.
Algorithm / Approach
- Include
<math.h>. - Initialize
value = 0. - Run a loop
ifrom 0 ton. - Calculate the power of 2 and add it to the running value:
value = value + pow(2, i). - Print the
value.
main.cpp
#include<iostream>
#include<math.h>
using namespace std;
int main() {
int n,value=0;
cout<<"Enter the Value for N : ";
cin>>n;
for(int i = 0; i< n; i++) {
value = value + pow(2,i);
cout<< value<<" ";
}
cout<< endl;
return 0;
}
Expected Output
Enter the Value for N : 5 1 3 7 15 31
Explanation of the Program
- This is a cumulative binary sequence.
- The powers of 2 are 1, 2, 4, 8, 16. If you keep a running sum of these powers (0+1=1, 1+2=3, 3+4=7, 7+8=15), you generate the mathematical formula (2n - 1).
Complexity
Time Complexity
O(n)
Space Complexity
O(1)