Java Program to print the following series. 1 3 7 15 31... n
Objective
Write a Java program to print the series 1, 3, 7, 15, 31 ... for N terms.
Algorithm / Approach
- Read the number of terms
nfrom the user. - Initialize an integer accumulator
xto 0. - Start a
forloop withi = 0up ton - 1. - In each iteration, calculate 2 raised to the power of
iusingMath.pow(2, i). - Add the powered result to
x. - Print
x.
Test.java
import java.util.Scanner;
class Test {
public static void main(String[] a)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter N: ");
int n = s.nextInt();
int x = 0;
for(int i = 0; i< n; i++) {
x = x + (int) Math.pow(2,i);
System.out.print(x+" ");
}
}
}
Expected Output
Enter N: 5 1 3 7 15 31
Explanation of the Program
- This series corresponds to the cumulative sum of powers of 2 (20, 21, 22...).
- Let's trace the logic: when
i=0, we add 20 (1) to x, giving 1. Wheni=1, we add 21 (2) to x (which was 1), giving 3. Wheni=2, we add 22 (4) to x (which was 3), giving 7. - Alternatively, you can notice that the i-th term in this series is always exactly 2i - 1 (for i starting at 1).
Complexity
Time Complexity
O(n)
Space Complexity
O(1)
Common Mistakes
- Forgetting to cast
Math.pow()to anint. The Math.pow function in Java returns a double, which cannot be directly assigned to an int without explicit casting.