Java Loops || HackerRank

 Problem Link:


https://www.hackerrank.com/challenges/java-loops/problem


Solution:

import java.util.*;
import java.io.*;
import java.util.ArrayList;

class Solution{
    public static void main(String []argh){
       Scanner sc=new Scanner(System.in);
       int t=sc.nextInt();
       while(t -->0){
           int a=sc.nextInt();
           int b=sc.nextInt();
           int n=sc.nextInt();
           int first=a+b;
            int res=first;
            System.out.print(first+" ");
           for(int i=1;i<n;i++){
               res=res+(int)Math.pow(2,i)*b;
               System.out.print(res+" ");
           }
           System.out.println();
       }
    }
}



Time Complexity: O(T*N)[For each of T test cases, we iterate till size ie n]

Space Complexity: O(T)[Depending on the number of test cases given]

Auxiliary Space: O(1)[No additional data structure is used]

Total Test Cases:6

Approach used:

Here we observe a pattern that every time Math. pow(2, i)*b gets added in the res.
While the initial value of res will be simply a+b

for i=0 res=a+b
for i=1 res=res+Math.pow(2,1)*b
for i=2 res=res+Math.pow(2,2)*b
for i=3 res=res+Math.pow(2,3)*b

--
--
--
--

till for i=n-1 res=res+Math.pow(2,n-1)*b

And we will print these values at every step.


"Thanks for Reading.😇"

"Share Further To Increase Knowledge Treasure.😊"




Comments

Popular posts from this blog

Solutions Of Practice Questions Dated 01-06-2022

CODEFORCES SPY DETECTED ROUND 713

Maximum Winning Score Geeks For Geeks