I just started programming and have taken too much time to code the solution for this problem:
In this problem you will test your knowledge of Java loops. Given three integers, \$a\$, \$b\$, and \$n\$, output the following series:
$$a + 2^{0}b, a + 2^{0}b + 2^{1}b, \ldots \ldots, a + 2^{0}b + 2^{1}b + \ldots + 2^{n-1}b$$
Input Format
The first line will contain the number of testcases \$t\$. Each of the next \$t\$ lines will have three integers, \$a\$, \$b\$, and \$n\$.
Constraints:
- \$0 \le t \le 500\$
- \$0 \le a, b \le 50\$
- \$1 \le n \le 15\$
Output
Print the answer to each test case in separate lines.
I just want to know whether this code can be further optimized in Java.
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
int r=0,c=1;
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
for(int i=0;i<t;i++){
int a=sc.nextInt();
int b=sc.nextInt();
int n=sc.nextInt();
r=a;
for(int j=0;j<n;j++){
if(j==0)
c=1;
else
c=c*2;
r= r +c*b;
System.out.print(r +" " );
}
System.out.println( );
}
}
}
r= r + c*b
is correct, as you will be addinga
too many times. \$\endgroup\$a
is added once. Are you thinking ofr += r + c*b
? \$\endgroup\$