- Practice
- Java
- Introduction
- Java Loops II
- Discussions

# Java Loops II

# Java Loops II

sauravdx007 + 38 comments I am not getting the question., Can anyone please explain what I need to do?

andythedandyone + 8 comments you are not alone... :P the question is a riddle itself.

abhaynabby1 + 7 comments it's a simple ques. you just need to print the series. look at series.. scan num=a and add 2^n.b and print.. as simple.

pabitrap03 + 4 comments i didn't get the why query (q) is used for can you please explain

sumit2303 + 1 comment the question checks the impllementation of loops. we have to run through a,b and n to get the desired output. Query specifies how many times we have to print the sequences.

You can break the problem by first getting one sequence, and then running it q times over.

yashpalsinghdeo1 + 1 comment here is solution of problem

**Java Loops II second**https://solution.programmingoneonone.com/2020/06/hackerrank-java-loops-ii-second-solution.htmlnandanambati + 1 comment class Solution{ public static void main(String args[]){ Scanner sc=new Scanner(System.in); int q=sc.nextInt(); for(int i=0;i

`s=(int)Math.pow(2.0,j)*b+s; System.out.print(""+s); System.out.print(" "); } System.out.print("\n"); } }`

}

komal_sga + 1 comment can you tell me why are we typecasting in this?

yashdamani1997 + 1 comment Math.pow() returns a double, and we need to store the result as int. That's why.

komal_sga + 0 comments ok thanks

arpan673523 + 0 comments it show that how many lines of geometric series will come (a+b(2^n-1))

ketanjoshi4477 + 0 comments it is just the no. of test cases.

navneetkrishna4 + 1 comment q is used for how many times you want to run the query

jadhavabhishek11 + 19 comments `int x=0; for(int j=0,k=0;j<n && k<=n-1;j++,k++){ x=(int)Math.pow(2,k)*b + x; System.out.print(a+x+" ");`

jadhavabhishek11 + 3 comments thank me later

kashyapsoni985 + 2 comments thanks

callenrwessels + 1 comment *nice*iamnaldo7 + 0 comments solved it?

iamnaldo7 + 0 comments have u solved it?

shashanknet50 + 0 comments [deleted]chetandaulani77 + 3 comments I solved the problem but solution is different but I am getting the output which is specified in explanation. import java.util.

*; import java.io.*; import java.lang.Math;class Solution{ public static void main(String []args){ Scanner in = new Scanner(System.in);

`int a =in.nextInt(); int b =in.nextInt(); int n =in.nextInt(); int s=0; s=s+a; for(int i=0;i<n;i++){ s+=(Math.pow(2,i))*b; System.out.print(" "+s); } }`

}

abhibs360 + 1 comment encountering newline everytime?

janishafi99 + 0 comments use print intead of println

veminenisusmith1 + 1 comment ur testcases are successfull??

veminenisusmith1 + 0 comments iam not getting these output please explain

nirajcit + 1 comment Hi chetandaulani77, please add System.out.println(); after the curlybrace which is after System.out.print(" " + s)

jasonyang545 + 0 comments nirajcit's comment is helpful and also change System.out.print(" " + s) to System.out.print(s+" ")

rishabhsinha85 + 1 comment hey explain use of j.

irazirfan + 0 comments [deleted]

irazirfan + 1 comment *smart one*Syed_Irfan_Ahmad + 4 comments I'm unable to print second line with this code. can you plz explain

www_harshasudha1 + 1 comment Add System.out.println(); after the loop so after completion of loop the next output will come in next line.

iamnaldo7 + 1 comment this doesn't work..

rawatabhinav99 + 0 comments Dont close the scanner function.

rdsatishkumar2 + 0 comments Use another variable to run second for loop instead of i

iamnaldo7 + 0 comments Same

jwilliams12 + 0 comments I had this same issue. I removed the line of code which closed the scanner. It was closing the scanner after the first loop and then causing subsequent loops to fail.

pramod5551 + 0 comments [deleted]Lucas_Artur + 0 comments wow !

pawan31 + 0 comments this is severely cool I'm totally blown ðŸ˜® away

Syed_Irfan_Ahmad + 0 comments Bro second line is not printing . there is some fault in it

patrorajesh70 + 0 comments i think k value is user defined , so need not to add in the for loop

karthiksquare + 0 comments here , in this code what is the need of declaring and initializing

int j=0 ...?

could you please explain

sonalisihra + 0 comments Can you please explain the function performed by variable k here.

iamnaldo7 + 0 comments this doesn't seperate the 2nd set of results in a new line. Everything is just in one line,,

borthakur_nilabh + 0 comments why j is necessary & why we need to type cast to int for x??

benkai + 0 comments [deleted]khodataev_v + 1 comment in your version, in loop j is redundant.

int result=0; for(int k=0;k<=n-1;k++){ result=(int)Math.pow(2,k)*b + result; System.out.print(a+result+" "); } System.out.println();

khodataev_v + 2 comments can also be removed k<=n-1; and replaced by k < n;

int result=0; for(int k=0;k<n;k++){ result=(int)Math.pow(2,k)*b + result; System.out.print(a+result+" "); } System.out.println();

khodataev_v + 0 comments and just for beauty: assign the your value x -> a, thereby removing this value from the output.

int result=a; for(int k=0;k<n;k++){ result=(int)Math.pow(2,k)*b + result; System.out.print(result+" "); } System.out.println();

veminenisusmith1 + 0 comments by using these i didnt get output it shows testcases fail it doesnt print second line

bhanuprakashgad1 + 0 comments what is purpose of declaretion of 'j'

Sriharismart0000 + 1 comment i am unable to print output in a single line

shudhanshusingh2 + 0 comments for single line use

System.out.print();

for new line

System.out.println();

praveen_aj2e + 0 comments @jadhavabhishek11 - what is the use of int j =0 ? when you already have k =0 which is useful to check the pow.

h1705231056 + 1 comment k here is an extra variable :- int s=a; for(int j=0;j

616akgupta + 0 comments what is your proble in this question

sameer_bisoyi + 0 comments Nice, but why is 'j' needed?

cs_ankitprajapa1 + 6 comments Everything is fine.. but what is q here.??

sanjanarocks97 + 5 comments i think q is used for number of series you want to print . Sample Input

`2 0 2 10 5 3 5`

here q=2 . which means 2 series. in 1st series a=0 b=2 n=10 and in 2nd a=5 b=3 c=5. i hope i m correct. (Newbie here)

arpan673523 + 2 comments yes you got it right

darshanmj99 + 0 comments awsome arpana

h19307 + 0 comments now i understood it , thanks man.

juliusmeldrin + 1 comment On the first series you have n and the second you have c? explain please

rohit8366 + 0 comments I think that is a typing error, in the second series the values are a=5, b=3 and n=5.

Hope this helps!!!!

tarique3751 + 0 comments for(int i=0;i

`} System.out.println(sb.toString());`

rohankumarthakr1 + 0 comments but actually what will be the equation will look like

Devishwash + 0 comments Yup this one is clear.

devendra_singh91 + 0 comments in the given test case q=2 an in next q=3 i.e. a+q^0b+q^1b.....

torok_chris + 0 comments It's super confusing, but "q" is taken care of for you and is actually called "t". Wtf! Yeah, I know.

bharath_bittu_39 + 0 comments no of test cases

[deleted] + 0 comments just to decide number of enteries

adityamishra66 + 0 comments int result=0; for(int k=0;k<=n-1;k++){ result=(int)Math.pow(2,k)*b + result; System.out.print(a+result+" "); } System.out.println();

ttanmayddas12 + 1 comment but sir this solution is not satisfying all the test cases.

devendra_singh91 + 1 comment i mean first you have to calculate the first term then see that the first term is common in all terms so you have to just appy a loop after that , and in that loop i have told that what we have to perform. Now just simply iterate that loop and multilpy that first term to the matter that you calculated inside the loop.

ashantanu821 + 0 comments u are correct bro..but i amnot getting the array declaration in java..can you help me?

wil_mcdowell15 + 1 comment In the U.S, when somebody says something is hard, you're not suppose to say, "its so simple look". xD

KeyGun + 1 comment whyï¼Ÿ

lepeckman + 1 comment It's true, that particular form of langue, in English as spoken & written in the USA, is derogatory. "It's so simple..." often includes a tone of rudeness.

But, it depends on how one uses it! Let's hope the meaning was: "This HackerRank problem could have been written more simply for the user to interpret, as the problem itself is much simpler than the tangled language as presented," rather than, "You must not be very bright, this is obvious and easy."

As HackerRank is directed towards people of all learning levels, I choose to believe the first option!

angel_garcia20 + 0 comments This also applies on spanish (but add "basically" every 10 words :) )

anujaysuyal23 + 0 comments Why q is used??

huzefakhan743 + 0 comments temp=a+b; for(int j=0; j

Nitesh651 + 1 comment import java.util.

*; import java.io.*;class Solution{ public static void main(String []argh){ Scanner in = new Scanner(System.in); int t=in.nextInt();

`for(int i=0;i<t;i++){ int a = in.nextInt(); int b = in.nextInt(); int n = in.nextInt(); int k=a; for(int j=0;j<n;j++) { k+=b*(int)Math.pow(2,j); System.out.print(k+" "); } System.out.println(); } }`

sukritisachan02 + 1 comment Hey!!My logic is same but I am not able to print second line(o/p of second test case dosent come),can you help me with this

shuklaannushka + 0 comments int tempAnswer = a; for (int j = 0; j < n; j++) { if (j == 0){ tempAnswer += a;}

`tempAnswer += (int) (Math.pow(2.0, j) * b); //tempAnswer+=a; if(a==0){ System.out.print(tempAnswer + " ");} else{ System.out.print(tempAnswer-a +" ");} } System.out.println();`

abhaynabby1 + 3 comments it's a simple ques. you just need to print the series. look at series.. scan num=a and add 2^n.b and print.. as simple.

kajulnisha_15cs + 4 comments how i can increment the number 'n' value for getting the series, i dont know how to put loop for this, can anyone plz help me

rohit8366 + 1 comment Hey,

Just keep on trying, the answer will come up, my algorithm was something like this create a "cumulative" variable and set it equal to user input "a" Inside the INPUT FOR Loop 1)Create a new for loop for a variable say "j", start it from 0 to n where n is the input provided by user and already written in the code. 2)compute the part of (2^j)*b and store it in a variable say "res". 3) Now simply add the equation to the cumulative variable -> cumulative=cumulative+res(refer step 2) 4) Print (cumulative+" ") 5) Close for loop 6) user proper Println syntax tomove cursor to next line.

v_lokeshkumar9 + 10 comments class Solution{ public static void main(String []argh){ Scanner in = new Scanner(System.in); int t=in.nextInt(); int v=0; for(int i=0;i

`for(int k=0;k<n;k++) { for(int j=0;j<=k;j++) v=v+a+(b*(2^j)); if(k!=n-1) System.out.print(v+" "); else{ System.out.print(v); } }System.out.println("\n"); v=0; } in.close(); }`

}

//can you help me where i went wrong

Santhosh3121995 + 0 comments class Solution{ public static void main(String []argh){ Scanner in = new Scanner(System.in); int t=in.nextInt(); for(int i=0;i

`}`

}

abhikapoor2000_1 + 1 comment you can not use ^ in java (i guess in programming ) use Math.pow(arg1,arg2) check this for more detail

check my code @ https://codeshare.io/arJ93q ask me if any issue or you can inhence my code -thank you

WolfOne + 1 comment You can use the '^' in programming. Python, Pearl, (not sure if on Ruby is possible) are some languages that support the use of '^'.

ayoubnadri + 0 comments isn't ^ XOR

vrishabshetty + 0 comments u cant add " a " sum it will disturb the sum just substitute and check

satyam_pandey571 + 2 comments ^ operator is not supported in java

emmonisha3 + 0 comments [deleted]emmonisha3 + 5 comments yes, instead of this use Math.pow() operator..... Hope this is helpful!!!!

for(int i=0;i

`int sum = a+b; for(int j=1; j<=n; j++){ System.out.print(sum+" "); sum+=((Math.pow(2,j))*b); } System.out.println(); }`

vinosiva_2001 + 0 comments smart and excellent

jumaev9 + 1 comment for Math.pow j has to be double, it won't work

rr_theprogrammer + 0 comments `use type cast (int)`

sjsouvik + 0 comments use type cast int as pow returns double and this code won't pass all the testcases. You need to use long to pass all the testcases

jayarajrajendri1 + 0 comments fabulous

atikul_islam_at1 + 0 comments please explain the code!

hamzararrani77 + 0 comments and also you have to display the answer in two lines you cannot enter the next line such as if you have two different set of values as answer you have to display them in two lines but with your program after that you are entering the third line

pradeepgour7777 + 0 comments [deleted]rememberthewhy + 0 comments you cant use to the power here(2^j) you have to use math.pow() function

Aarkay360 + 0 comments that a is added n times in last term of series and n-1 times in second last term of series and n-2 times in third last term of series ...... ..... ..... and a is added only once in each term of series. So u can print System.out.println(v+a); instead of adding the a in each term.

harsh104356 + 0 comments println itself means a new line so make it like

System.out.println();

angel_garcia20 + 0 comments Everything

devendra_singh91 + 0 comments i mean first you have to calculate the first term then see that the first term is common in all terms so you have to just appy a loop after that , and in that loop i have told that what we have to perform. Now just simply iterate that loop and multilpy that first term to the matter that you calculated inside the loop.

anujdada532 + 0 comments same with me

suryavenkat7373 + 0 comments where are you working??

ttanmayddas12 + 0 comments but it doesn't pass through all the test cases.

mpooja1062000 + 0 comments yes! but test cases are not satisfiying

arpan673523 + 0 comments Riddle is solved, Check the solution above

imAnmolPal + 0 comments [deleted]strangerHash + 1 comment class Solution{ public static void main(String []argh){ Scanner in = new Scanner(System.in); int t=in.nextInt(); for(int i=0;i

`//x=x+(((int)Math.pow(2,i))*b); r=r+(((int) Math.pow(2,j))*b); System.out.print(r+" "); } System.out.println(); } in.close(); }`

}

i have put down solution here check it

pankajkandpal751 + 0 comments 9 errors compilatation failed

somanisingh21 + 1 comment [deleted]somanisingh21 + 1 comment import java.util.

*; import java.io.*;class Solution{ public static void main(String []argh){ Scanner in = new Scanner(System.in); int t=in.nextInt(); for(int j=0;j

`System.out.print(a+" "); } System.out.println(); } }`

}

somanisingh21 + 0 comments Here t is for the number of test cases as in the first loop.And n is the upper bound of your series which is in the second loop.

dineshkoppula321 + 0 comments We need to print the given series upto n terms

nirbhay0299 + 0 comments `int res=a; for(int j = 0;j<n;j++){ res += Math.pow(2,j)*b; System.out.print(res+" "); } System.out.print("\n");`

nherron + 0 comments You have to look at the equation at the top. That is the trickiest part.

satya_chk + 5 comments a+2^0*b+2^1*b+2^2*b+2^3*b+........+2^n-1*b

In every Iteration you should add previous result so that you would get result .................................... 1st Iteration: result=a+2^0*b ......................... 2nd Iteration: result = result + (2^1)*b ......................... 3rd Iteration: result =result + (2^2)*b ........................ N^th Iteration: result = result+ (2^n-1)*b ...........I hope It will help you!!!!!!!

gmpgiri + 2 comments Thank you. Solved the problem now!

vjitesh + 1 comment Will you tell me the Code how it solved.

rajat_chouksey07 + 14 comments for (int j = 0; j < n; j++) { a += b; System.out.print(a + " "); b *= 2; } System.out.println();

0_abhi + 0 comments Thanks for sharing, found it very simple to understand.

farkas_krisztia1 + 0 comments Not sure why it's been down voted. It's a brilliant solution. Helped me a lot to understand what's going on. Thanks mate

harishhp53 + 1 comment Out of all the complicated solutions, you gave the simplest solution ever. Brilliant thinking! Thanks for sharing.

rohit8366 + 0 comments I am glad my comment helped you ! Keep Coding :D

ashita_gaur + 0 comments [deleted]ankitkumarw12 + 0 comments really you make it very simple...too good

chakhil02 + 1 comment i didnt understand your logic can u explain it please

devendra_singh91 + 0 comments i mean first you have to calculate the first term then see that the first term is common in all terms so you have to just appy a loop after that , and in that loop i have told that what we have to perform. Now just simply iterate that loop and multilpy that first term to the matter that you calculated inside the loop.

officialmailsgi1 + 0 comments Just brilliant!!!

TinchoDS93 + 0 comments LOL! I've made a "local" class similar to pow... XD (And completed the test) But... omg your answer were soo simple and efficient...

mvdeshpande28 + 0 comments This is the best. I was using Math.pow unnecessarily.

manojmnk123 + 0 comments good logic but it's is not working giving some runtime exception .

sarthakgupta98 + 1 comment i just want to know that how does your power increments for 2 in this code

pooja_daredi + 1 comment for(int i=0;i

`int r=a; for(int j=0;j<n;j++) { r=r+(((int) Math.pow(2,j))*b); System.out.print(r+" "); } System.out.println();`

look at this

v_lokeshkumar9 + 1 comment but in that case we would get a space after the last element. but accroding to test case (given) we should not get a space after last element. so how can you modify without getting a space at end the end in your code

tarique3751 + 0 comments you can run and check, if in test case space is not allowed after last element you can add space till n-1 length and skip for other.

ajay_2606 + 0 comments thanks for helping us.

Noxsser + 0 comments This....this code works and I still struggle to figure out what it does until I had to write it out on paper to compare with the logic of the equation as the equation requires 2^n.

After several tries and a few hours burn away I finally get it.

nagaajay9535 + 0 comments sure you are going to be a gem programmer. may be by now you are i think . great buddy.All the best. nice code ,good coder.

SinghJaspreet95 + 0 comments [deleted]

shivammahajan98 + 1 comment But by this logic it will add 'a' each loop we only have to add 'a ' first iteration only....

razvanodenie + 0 comments Great point! I was adding 'a' at each iteration and couldn't figure out why the results were wrong.

16JG1A1242IT + 0 comments then y did i get wrong output here?

class Solution{ public static void main(String []argh){ Scanner in = new Scanner(System.in); int t=in.nextInt(); int s=0; int j; for(int i=0;i

rishabhstc + 0 comments superb explanation

vrushabhuprikar + 0 comments thank you

vinityadav + 16 comments int A = 5; int B = 3; int loop = 5;

`int tempAnswer = A; for (int j = 0; j < loop; j++) { tempAnswer += (int) (Math.pow(2.0, j) * B); System.out.print(tempAnswer + " "); }`

rathoreabhi1990 + 6 comments It will not work. First line i.e. int tempAnswer = A; It will fail.

meet_alexmac + 0 comments [deleted]chaitanya492 + 3 comments yes, u are right,, but what is the reason behind it??

Zeeshan1996 + 0 comments [deleted]geo_sam_ca + 1 comment It should be an "a".

Mitprajapati + 2 comments int tempAnswer = 0; for (int j = 0; j < loop; j++) { tempAnswer += (Math.pow(2, j) * b); System.out.print(tempAnswer + a + " "); }

rajmetre92 + 0 comments nice

ayu_agr2011 + 1 comment when i write tempAnswer = tempAnswer + (Math.pow(2,j)*b); it gives an error of loss of precision. Can you please explain me why is it so?

lakshmi_bhavani1 + 1 comment pow() gives a double value,but you are using an integer so the precision is lost..Type cast the pow() function to integer . You will get it done.

ritabandas2000 + 0 comments In case you haven't noticed, first you need to take all the inputs and then output according to each of them. Not, give the output after every, input.

sherzodkh + 2 comments [deleted]goyallovish52 + 1 comment what is the need of taking two seperate variables: storage and formula

sherzodkh + 0 comments [deleted]

16bce169 + 2 comments If you use "println" then every number will be printed in next line..........

public static void main(String []argh){ Scanner in = new Scanner(System.in); int t=in.nextInt(); for(int i=0;i

`int sum=0; sum += a + (pow(2,0)*b); System.out.print(sum+" "); for(int j=1;j<n;j++) { sum = sum + (b*pow(2,j)); System.out.print(sum+" "); } System.out.println(); sum=0; } in.close(); } static int pow(int a,int b) { if(b>0) { return(a*pow(a,b-1)); } else { return 1; } }`

TyagiLalit + 1 comment VIT VIT VIT

mech_engg + 0 comments Lol

16JG1A1242IT + 0 comments ***then y did i get wrong output here? ***class Solution{ public static void main(String []argh){ Scanner in = new Scanner(System.in); int t=in.nextInt(); int s=0; int j; for(int i=0;i

piyushmanglani08 + 0 comments it will work and it works properly dude.

LALIT4960 + 3 comments `int tempAnswer = A; for (int j = 0; j < loop; j++) { if (j == 0) tempAnswer += a; tempAnswer += (int) (Math.pow(2.0, j) * B); System.out.print(tempAnswer + " "); } This will work as we need to add a in the first instance only`

A_Band + 0 comments YOur Code is aWesOmE.

pprathameshmore + 0 comments Your code is helpful!

chainani_navin97 + 1 comment bro u logic is wrong

satyam_pandey571 + 0 comments how??..can u explain me?

Etcetra + 0 comments take in small case alphabets i.e. "a"

itikalamadhavi01 + 0 comments [deleted]

linayaseen + 0 comments [deleted]meet_alexmac + 2 comments This solution is what I considered at first too, but if you do this, you will end with a trailing space. It's better to print hte first number (a + 1 * b) and then print " " + newAnswers in your loop.

ali_shahri + 6 comments This one works as it should I guess:

import java.util.

*; import java.io.*;class Solution{ public static void main(String []argh){ Scanner in = new Scanner(System.in); int t=in.nextInt(); for(int i=0;i

`public static void doJob(int a, int b, int n){ int result=0; result = a+result; for (int i = 0 ;i<n;i++){ result =result + (int)Math.pow(2, i)*b; System.out.print(result + " "); } System.out.println(); }`

}

dshekhar477 + 4 comments why do we need int before Math.pow

johnmlhll + 2 comments You are using

int result

to find a power of value of the result variable using

Math.pow()

which returns a double value as a library method. You thus need to cast it to an int in order for it to work/compile. You will get a casting error otherwise.

abhijit0502 + 0 comments pow() takes both of its arguments as double.

aniketsarkar26 + 1 comment pow() results in double

616akgupta + 0 comments double and int

Thanmai_T + 0 comments That implies type casting

rangareddy171 + 0 comments type casting

Atomsmasher124 + 0 comments that int is needed for type casting or for converting double data type to int type , as we know that Math funcction is of double..

sumit_jethva36 + 1 comment Good solution.But inorder to run another test case make sure to add result = 0; after System.out.println(); otherwise it will take previous result value for another test case.

shubhsrivastava2 + 0 comments exactly.

shreya_goel2015 + 0 comments why are you creating another method? Why not do the same thing in main method?

rohitsharma68381 + 0 comments it fails not work

muskanbansal978 + 0 comments According to me best solution

16JG1A1242IT + 0 comments ***then y did i get wrong output here? ***class Solution{ public static void main(String []argh){ Scanner in = new Scanner(System.in); int t=in.nextInt(); int s=0; int j; for(int i=0;i

domaners + 1 comment You can use the .trim() method on your output string to remove the trailing space:

int runningTotal = a; String outputString = ""; int multiplier = 1;

for(int count = 1; count <= n; count++) { runningTotal += multiplier * b; outputString += runningTotal + " "; multiplier *= 2; }

System.out.println(outputString.trim());

kent_h + 0 comments It solves the problem of a^(count-1). Thank you.

aashayoo9 + 0 comments import java.util.

*; import java.io.*; import java.lang.*;class Solution{ public static void main(String []argh){ Scanner in = new Scanner(System.in); int t=in.nextInt(); int x=0; int y[]=new int[15]; for(int i=0;i

`in.close(); }`

}

s_k_r + 1 comment why have you subtituted (int) in the line no 3?

rishabh_hurr + 0 comments for converting double to int

rishabh_hurr + 0 comments converting from double to int becoz pow function gives the double value got it ??

gjayaraj18031998 + 0 comments maybe in the first line int tempAnswer = 0;

mar87 + 0 comments Thanks vinityadav !! it works! private static String answer(int a, int b, int n){ String answer = ""; int tempAnswer= a; for (int i = 0; i < n; i++) { tempAnswer += (int) (Math.pow(2.0, i) * b); respuesta = respuesta+ " " + tempAnswer; }

DanYoo940 + 1 comment what is +=??

sleepycloudtodd + 1 comment increment the value on the right by the value on the left( so i += j means increment j by i). :) This website seems pretty snobby condsidering the questions asked, how they are explained, and how people talk to each other in the discussions. I did a code camp and know some fairly tricky things and most of these questions seem designed for those who either have math degrees or those who already know a lot about Java and want to keep their skills sharp. "Easy"? Sure... How would a Java beginner even know there is a Math.pow method to import?

Anyway, check out codingbat.com for more straightforward questions that actually range from beginners to advanced. Also look into codecademy.com. Really great resources for FREE.

DanYoo940 + 0 comments dang this helps a lot. Thank you so much

Yogesh_Ganpule + 0 comments you made it more complex

kritikapatel111 + 0 comments import java.util.

*; import java.io.*;`} System.out.println(""); } in.close(); }`

}

rajat_chouksey07 + 0 comments dont use Math.pow function.

ranjiece98 + 0 comments tq

n140695 + 0 comments Thank you :)

18505A0510 + 0 comments It's wrong bro

devenders0309 + 0 comments [deleted]

nahomagidew + 0 comments [deleted]Liswin + 0 comments [deleted]mysidia + 2 comments I solved this.... I believe the "EASY" level classification is incorrect, Because this question requires significant extra analysis And an understanding of mathematical series to approach.

The question in the way that it's written will not be accessible to most beginning and intermediate programmers, unless you have an academic background in Applied math, discrete algebra, or Calculus.

Anyways, they're looking to provide you A list of "a", "b", "n" values, and repeat this process q times.

Each time you get a list of a, b, n values, they want you to print out the integer Sum which you get when you add up 'n series terms' from the expression.

The first series term is

a + 2^0 * b

The second series term is a + 2^0 * b + 2^1 * b

This process repeats up to "n", and the n-th series term is

a + 2^0 * b + 2^1 * b + .... + 2^(n-1) * b

Your loop just needs to show the cumulative sum on each series term

I suggest working it out on paper with the sample inputs before writing the program.

sahil00941 + 1 comment its easy peasy

ewhitedev + 0 comments Easy for someone with a degree in mathematics. Algorithms aren't "easy".

code4bronson + 1 comment Great explanation!

vnaykanswal55 + 0 comments thanks

nishanthduvva + 0 comments [deleted]vickyvignesh384 + 0 comments import java.util.

*; import java.io.*; import java.math.*;class Solution{ public static void main(String []argh){ Scanner in = new Scanner(System.in); int t=in.nextInt(); int s=0; int v=0; for(int i=0;i System.out.print(v+" ");

`} System.out.println(); s=0; v=0; } in.close(); }`

}

this code works fine

johnmlhll + 0 comments Me neither.. not a scooby doo on what I was been asked. Some of the contributions below shone a light on what was been asked and made it possible to solve.....

thrinath999 + 0 comments import java.util.

*; import java.io.*; import static java.lang.Math.pow; class Solution{ public static void main(String []argh){ Scanner in = new Scanner(System.in); int t=in.nextInt(); for(int i=0;i } in.close(); } }xooBEE + 0 comments dear look at the qustion carefully.....when u focus on it u get more issues and problems but behind that once a time will came ur one confiusion converts to an answer.this remarks the sucess........take difference of its answer u will get solution

akshayakki + 0 comments this is what i got:

for(int i=0;i

deekshithsagar73 + 0 comments NOO

UserNameDhru + 0 comments [deleted]UserNameDhru + 2 comments You need to take the value of a, b and n and create a series of ans using this (a + 2^0 * b),..., (a + 2^0 * b + 2^n-1 * b)

q is just tells the number of quires you'll be performing, if q is 3 then you'll have to create 3 sereies of ans using the series that they have given you.

q = 3;

a = 0 b = 2 n = 10

a = 5 b = 3 n = 5

a = 1 b = 8 n = 3

[2, 6,..., 2046]

[8, 14,...,98]

[9, 25, 57]

n will tell you how long will series of ans will be. a = 0; b = 2 ; n = 10; (0 + 2^0 * b), [(0 + 2^0 * b) + (2^1 * b)] ... (0 + 2^0 * b + 2^1 * b + a + 2^0 * b ) Your series of ans be [2 , 6 ... ans]

The catch in the series is you only need to add the new 2^n-1 to the previous calculation you did.

import java.util.*; import java.io.*; class Solution{ public static void main(String []argh){ Scanner in = new Scanner(System.in); int t=in.nextInt(); for(int i=0;i<t;i++){ int a = in.nextInt(); int b = in.nextInt(); int n = in.nextInt(); int count = 0; int constant = 0; int sum = 0; while(count < n){ if(count == 0){ constant = 1; sum = a + (constant*b) + sum; }else{ constant = constant * 2; sum = (constant * b) + sum; } System.out.print (sum + " "); count += 1; }//end while System.out.println(); } in.close(); } }

jiaullah94 + 1 comment This program is working fine, but constant value =0 you defined already right? If count !=0 then, constant will become 0*2 =0 and it will continue right? can u please explain how it is working.

IdiotTester + 0 comments the value of constanst is 1 after first execution

ranggageni + 0 comments this code almost correct, i try this code but the result is one excess, how to fix it ?

shray + 0 comments for(int i=0;i

bikashpokhrel33 + 0 comments same here :D

omyoo7 + 1 comment Here is full code: but please first understand it before use...

import java.util.

*; import java.io.*;class Solution{ public static void main(String []argh){ Scanner in = new Scanner(System.in); int t=in.nextInt(); int temp = 0; for(int i=0;i for(int j = 1; j <= n; j++){ temp += (int)(Math.pow(2, j-1) * b); System.out.print((a + temp) + " "); } temp = 0; System.out.printf("\n"); } } }

onwuchekwalucas + 0 comments System.out.print((a + temp) + " ");

was really helpful

przemyslawg91 + 0 comments int replace = 0; for (int j = 0; j < n; j++) { int math = (int) Math.pow(2, j); int sum0 = (math * b); int ver = sum0; replace += ver; int asd = a + replace; System.out.printf("%d ", asd); } System.out.println(""); } in.close();

rajarshikundu5 + 0 comments test71213 + 0 comments for each of the 'q' queries you are given three values - (a,b,n)

- Task is to print a series with 'n' space separated terms where i(th) term is of the form =>>
**( a + (b * (2^i)) )** - Print such a sequence for each of the queries in new line. Thats all

- Task is to print a series with 'n' space separated terms where i(th) term is of the form =>>
mohammadaslampa1 + 0 comments Yah, It's a simple question to loop and print a series of the form (a+1*b)+(a+1*b+2*b)+(a+1*b+2*b+4*b)+...........

You need to append always Math.pow(2,j) times b i.e 2^1*b,2^2*b....

kaustabh_sinha97 + 4 comments `public static void main(String []argh){ Scanner in = new Scanner(System.in); int t=in.nextInt(); for(int i=0;i<t;i++){ int a = in.nextInt(); int b = in.nextInt(); int n = in.nextInt(); int seq = a + (int)Math.pow(2, 0) * b; System.out.print(seq + " "); for (int j = 1; j < n; j++){ seq = seq + (int)Math.pow(2, j) * b; System.out.print(seq + " "); } System.out.println(); } in.close(); }`

kaustabh_sinha97 + 1 comment Hope it helps.

jeniousalok + 0 comments Very nice and clean code buddy..

ranggageni + 1 comment it's works, good job

vnaykanswal55 + 0 comments thanks

ramya_9 + 0 comments can u please tell me why you took.....for(i=0;i

dubrovAI + 0 comments Thank you for that great and simple idea.

vnaykanswal55 + 0 comments import java.util.

*; import java.math.*; class sos { public static void main(String args[]) { Scanner sc=new Scanner (System.in); int i,n,a,j,b,k=0,l,s1; l=sc.nextInt(); for(int m=0;m=1&&n<=15) { for(i=0;i=0) s=s+a; k++; //if(k%10!=0) s1=(int)s; System.out.print(s1+" "); //else //{ //System.out.println();`//} s=0; }} System.out.println(); } }`

}

lavish173_ + 0 comments for(int i=0;i System.out.println(""); } }

pratyush3105 + 0 comments [deleted]yoftahe_samson + 0 comments This might help a bit :)

ONLY the first itteration uses the value of a.

Therefore, The first output value is: (a + 2 ^ 0 + b)

for the next itteration you just add the value of (2 ^ 1 * b) on the previous itteration value. then you just keep adding up to (2 ^ i * b), I is only up to the n value.

angel_garcia20 + 0 comments The problem is nothing more than a series, because of course why not. You can do it via an inner for-loop, a while-loop or a do-while, which kinda seems apropiate, tho, too lazy to show it, or use a do-while.

anujaysuyal23 + 0 comments for(int j=0;j

`} System.out.println( );`

srivastavajahnv1 + 0 comments the question says that their are number of queries and for for each query their is differnt set of value of a,b,n the sum in given format calculate them t times(wher t is number of queries) for(int i=0;i

`} in.close(); }`

}

adarsh_kumar_ya1 + 0 comments //here is the solution

class Solution{ public static void main(String []argh){ Scanner in = new Scanner(System.in); int t=in.nextInt();

`for(int i=0;i<t;i++){ int a = in.nextInt(); int b = in.nextInt(); int n = in.nextInt(); double sol=0; for(int k=0;k<n;k++) { for(int j=k;j<=k;j++) { sol=sol+(Math.pow(2,j)*b); } int value=(int)sol; System.out.print((value+a)+" "); } System.out.println(); } in.close(); }`

}

LightCpp + 0 comments the question want you to print each value of the expressions,from 0 to n-1, and dont forget the blank and change line

Ramsannidhi + 0 comments int x=0; for(int j=0;j

`//try this`

ashutoshk431 + 0 comments for(int j=0;j

`for(int i=0;i<n;i++) { result=result + (int)((Math.pow(2,i))*b); System.out.print(a+result); System.out.print(" "); } System.out.println(); }`

aditya6752 + 0 comments you just need to take input of three values . now question comes for how much time then that is ansewred by no of queries.. after that simply follow additon property by using+= thing

dalinjeevan9 + 0 comments for(int i=0;i

`System.out.print(""+s+" "); } System.out.println(); }`

shreshth14_1999 + 0 comments check my solution here https://shreshth141999.wixsite.com/notaprogrammer/post/hackerrank-java-solutions-easy

steveperkins + 4 comments This is an absolute joke. My code worked on the first try, but the exercise was:

5% - Demonstrating the ability to write a two-level nested "for" loop in Java.

95% - Getting your mind back into the mode of undergraduate algebra, and deciphering this ridiciously contrived number series.

For this website to have any meaningful value at all, that emphasis should really be the reverse.

cjones88 + 0 comments Agreed.

grumpy_riddle + 1 comment as you will find, programming has to do A LOT with math; but they gave to you all the tools to complete it, the key is to start thinking like a computer and do the calculations; because programming = calculations.

prt397 + 0 comments Agreed with you

aratan + 2 comments Maths is key of software developement. U must have knowledge of this.

steveperkins + 0 comments Number one... I've been a professional software developer for over 20 years. I assure you that number series puzzles will be irrelevant to the work that 99%+ of you will ever do.

Number two... written communication is key to a software development career. Therefore, should this site design programming exercises whose

*primary*challenge is teaching you how to spell properly?Of course not. The primary purpose of this exercise at this point in the series is to develop or demonstrate mastery of two-level nested loops. Extraneous material that renders this primary purpose secondary only weakens the effectiveness of this exercise.

mysidia + 0 comments There is math involved for sure, But real-world programming rarely or Never involves a task like the one described in the highly-contrived problem.

Anyways: A simple rule should be observed.... If you want to write a math problem, your own math and use of mathematical language should be written as a Clear, and sensical question using conventional language and notation.

Although the main contention with this problem is that the language is a bad explanation of what answers are to be provided by the solution.

The authors printed some formulae in the description but used an informal approach. They also used the word "series" incorrectly.

"print the series corresponding to the given a, b, and n values as a single line of n space-separated integers."

Since a series is by definition "An Infinite sum", "Printing a series as a sequence of integers" is nonsensical.

Frankly, at first glance, the notation used is a bit wonky. Usually you also don't use commas to separate your partial sums; You would list them on separate lines.

It's not clear from the question statement that the author is in fact even looking for the list of partial sums from 1 up to N, and that N is also the number of terms. You have to read between the lines.

Finally, After the end of the problem description and start of the Input Format, here comes an unexplained value called "q" for "Number of queries", Which seems superfluous, since the problem statement above did not mention how this is to be used.

So you're essentially left coming up with a theory on what the problem is to be solved, And testing a bunch of mathematics out on paper to see if the sample inputs and outputs agree with what you think they wanted to say they wanted.

For real-world programming: usually, when anything beyond simple arithmetic is involved in terms of math, this will be math that the programmer has constructed or processed on their own to efficiently solve a problem --- in some cases you may have a formula to evaluate With user-provided inputs, rarely you might even have an iterative process to evaluate to achieve a summary result, But in the real world they're sure as hell not going to ask you for terms of a series you are computing; not unless you're stepping through it for debugging or in a programming domain specialty is developing mathematical modeling equations, or something similar as that.

hivex201 + 0 comments true x)

sharmatushar124 + 17 comments Guys, done without creating another object please checkout

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

synhack + 4 comments That's good. You can simplify even further if you realize that 2^0 + 2^1 + ... + 2^j = 2^(j+1) - 1

class Solution{ public static void main(String []argh){ Scanner in = new Scanner(System.in); int t=in.nextInt(); StringBuilder sb = new StringBuilder(); for(int i=0;i<t;i++){ int a = in.nextInt(); int b = in.nextInt(); int n = in.nextInt(); sb.setLength(0); for(int j=0; j<n; ++j) { // 2^0 + 2^1 + ... 2^j = 2^(j+1) - 1 sb.append((int) (a + b*(Math.pow(2, j+1) - 1))).append(" "); } System.out.println(sb.toString()); } in.close(); } }

Liswin + 2 comments What does variable 't' hold in this program?

sleepzilla23 + 1 comment The number of queries, which is the integer on the first line of the input.

ayushbarnawal48 + 1 comment then what's about n? I'm confuse in between these two. Can you please explain.

_Syarif_ + 0 comments 2 3 3 4 5 6 5 7 n = 8

jangraamit002 + 0 comments to get q

mysidia + 4 comments I didn't need to call the Math.pow() function.

I used

for(x = 0; x < n; x++) { result = a; for(h = 0; h <= x; h++) result += (1<< h) * b; if ( x > 0) System.out.printf(" "); System.out.printf("%d", result); } System.out.printf("\n");

sruthi_15821 + 1 comment what does this line(

**result += (1<< h) * b**) do? what is the role of**<<**operator?mysidia + 2 comments a += b; is the same as a = a + b;

(1<<h) Starts with 2 to the zeroth power, a binary 1, Shifts the number to the left by h binary bits, e.g 00000001 in binary left shift 1 becomes 00000010, left shift 2 becomes 00000100.

Left-shifting a binary number by 1 bit position multiplies that number by 2. Left-shifting by 2 multiplies by 2^2. Left-shifting by 3 multiplies by 2^3, etc.

sruthi_15821 + 0 comments thankyou..

niktor + 0 comments nice idea with the binary shift!

nagireddy030493 + 0 comments for(int i=0;i

`sum= sum+b; System.out.print(sum+" "); b=2*b; } System.out.println(""); } in.close();`

sisolta75 + 0 comments Should be h<=x+1

code4bronson + 0 comments best Answer Yet!

gourabinda + 0 comments whats that String builder means?

raziashaik61 + 0 comments Could you please explain me about below three lines: 1. StringBuilder sb = new StringBuilder(); 2. sb.setLength(0); 3. sb.append((int) (a + b*(Math.pow(2, j+1) - 1))).append(" ");

PaviChandren + 1 comment Is Math.pow() an inbuilt function in JAVA?

rowansiwakoti + 1 comment Yes

chauhanshreya39 + 1 comment what is the function of math.pow

dave_balazs + 0 comments math.pow(2, 3) is 2^3 (3rd power of two) and will result in 8. Basic math.

govardhan271 + 0 comments excellent

samyak_jain7172 + 1 comment Sir, It dosen't Work.The line"System.out.println("");"does not change the line for 2nd input.

chandanhtc_adit1 + 0 comments make sure, it is after the block.

Sunjoker + 0 comments I also do this,but it is wrong!Why?

akhil_singh_as70 + 0 comments here a = a + (int)Math.pow(2,j)*b;

why we used a= a +

**__**: can we use another integer like int c=0; c= a + (int)Math.pow(2,j)*b;if not please explain

rustamraj101 + 0 comments why u use t integer variable here?

vinaykrishna931 + 0 comments Clear and Perfect...!! Thanks

chamzz + 2 comments Yes.This is correct. But I have one question... In the series we can see evey value is multiply by b.(

**either first a also**).But in your code I can't see that. But your one gives correct answer. Can you please explain that for me?*I used this and this gives wrong answerI can't realize why it is wrong???*import java.util.*; import java.io.*; class Solution{ public static void main(String []argh){ Scanner in = new Scanner(System.in); int t=in.nextInt(); for(int q1=0;q1<t;q1++){ int a = in.nextInt(); int b = in.nextInt(); int n = in.nextInt(); int ans=a+1*b; for(int j=0;j<n;j++){ int x=2^j*b; ans+=x; System.out.print(ans+" "); } System.out.println(); } in.close(); } }

rcardoso + 1 comment This line:

int ans=a+1*b;

Should be:

int ans = a;

Since you're loop from 0 you code is calculating a + 2^0*b twice and you will get a wrong result.

And this line:

int x=2^j*b;

The '^' it xor (exclusive or) operator not pow operator. You have to use

`Math.pow();`

or a shift operation.aksha_v95 + 0 comments Thank You. I have used the shift operation as you said but two test cases failed out of 5. Could you please help me with this code?

class Solution{ public static void main(String []argh){ Scanner in = new Scanner(System.in); int t=in.nextInt(); for(int i=0;i<t;i++){ int a = in.nextInt(); int b = in.nextInt(); int n = in.nextInt(); int first = a+b; int sec = (2*b)+first; System.out.print(first+" "+sec+" "); int sum = sec; for(int j=1;j<=n-2;j++){ int s = ((2<<j)*b); sum = sum + s; System.out.print(sum+" "); } System.out.println(" "); } in.close(); } }

luiejohnmalimit + 0 comments [deleted]

Pricks_123 + 0 comments Thanks #sharmatushar124 for ur Soln.

jeya28798 + 0 comments but what i the need of 't' here

sgic2001 + 0 comments silly me, i was calculating each term individually (3 nested for loops instead of 2) which would increase time complexity alot. Thanks xD

abazar786 + 1 comment `public static void main(String []argh){ Scanner in = new Scanner(System.in); int num1, num2=0; int t=in.nextInt(); for(int i=0;i<t;i++){ int a = in.nextInt(); int b = in.nextInt(); int n = in.nextInt(); for(int k=0;k < n; k++){ num1 =a; num2 += (Math.pow(2,k)*b); System.out.print(num1 + num2 + " "); } } in.close(); }`

I have two question first why is this not working and why did he use (int) beofre Math.pow(). Thank You

sgic2001 + 0 comments Math.pow returns a double. To store it in an int variable you have to typecast it to int {putting (int) before the value} typecasting a double to an int removes all the digits after the decimal. 12.25 becomes 12 13.99 becomes 13 14.00 becomes 14

15h61a04831 + 0 comments System.out.print(a + " "); System.out.println(""); can you please explain this and this

Shivam_Jha29 + 0 comments Thanks .It's working without any error.

chandrashekarvt1 + 0 comments why are we assigning the value to a?

sharmadeepankar + 0 comments Hi,

What is the relevance of the below statement in the Program.Please explain.

System.out.println("");

RodneyShag + 9 comments ### Java solution - passes 100% of test cases

If using Math.pow(), make sure you cast it to an integer since it returns a double.

import java.util.Scanner; class Solution{ public static void main(String [] args) { Scanner scan = new Scanner(System.in); int t = scan.nextInt(); for (int i = 0; i < t; i++) { int a = scan.nextInt(); int b = scan.nextInt(); int n = scan.nextInt(); for (int j = 0; j < n; j++) { a += b * (int) Math.pow(2, j); System.out.print(a + " "); } System.out.println(); } scan.close(); } }

From my HackerRank Java solutions.

kunnu120 + 2 comments Can you please explain what does this line do? a += b * (int) Math.pow(2, j);

RodneyShag + 3 comments a += b * (int) Math.pow(2, j);

is shorthand for

a = a + b * (int) Math.pow(2, j);

Math.pow() is a function that is provided to us by Java. Here, it takes 2 parameters. When I pass in

**2**and**j**, it does exponentiation (known as "power") as 2 to the j-th power. For example, Math.pow(3,5) = 3 * 3 * 3 * 3 * 3.Also, Math.pow() returns a

**double**instead of an**int**. We "cast" it to an integer by putting(int)

in front of it. We cast our result since

**a**is an integer type and we can only assign an**int**type to it.Hope this helps.

kunnu120 + 1 comment Thank you very much for explaining me.

kunnu120 + 2 comments what's wrong with this? can you please tell me

`class Solution{ public static void main(String []argh){ Scanner in = new Scanner(System.in); int t=in.nextInt(); for(int i=0;i<t;i++){ int a = in.nextInt(); int b = in.nextInt(); int n = in.nextInt(); for (int j = 0; j < n; j++) { int c = a + b * (int) Math.pow(2, j); System.out.print(a + " "); a = c; } System.out.println(); } in.close(); } }`

RodneyShag + 0 comments I think the values for "a" and "c" are incorrect inside the inner for loop.

lata_lingadal + 1 comment where the value of t is used ?what is neccesary of it in this code....

kunnu120 + 0 comments t is number of test cases

vikaskumar_vsk + 0 comments

Sort 1913 Discussions, By:

Please Login in order to post a comment