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

# Java Loops II

# Java Loops II

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

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

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.

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

sumit2303 + 0 comments 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.

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.

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

sanjanarocks97 + 2 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 + 0 comments yes you got it right

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!!!!

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

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?

abhaynabby1 + 2 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 + 3 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 + 0 comments 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.

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

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

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

anmolpal1999 + 0 comments [deleted]

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

satya_chk + 2 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 + 7 comments for (int j = 0; j < n; j++) { a += b; System.out.print(a + " "); b *= 2; } System.out.println();

abhishekjohri98 + 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!!!

SinghJaspreet95 + 0 comments [deleted]

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

vinityadav + 15 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 + 5 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 + 0 comments 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.

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

sherzodkh + 0 comments [deleted]

16bce169 + 1 comment 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

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

LALIT4960 + 2 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`

np_assignment + 0 comments YOur Code is aWesOmE.

pprathameshmore + 0 comments Your code is helpful!

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

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 + 5 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 + 0 comments pow() results in double

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 + 0 comments 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.

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

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());

kwhwj + 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.*;class Solution{ public static void main(String []argh){ Scanner in = new Scanner(System.in); int t=in.nextInt(); for(int i=0;i

`} System.out.println(""); } in.close(); }`

}

rajat_chouksey07 + 0 comments dont use Math.pow function.

ranjiece98 + 0 comments tq

n140695 + 0 comments Thank you :)

swethareddypoth1 + 0 comments It's wrong bro

nahomagidew + 0 comments [deleted]Liswin + 0 comments [deleted]mysidia + 1 comment 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".

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 + 1 comment 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

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();

rishikundu6 + 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 + 1 comment `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 + 0 comments Hope it helps.

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 + 11 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 + 3 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 + 1 comment 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

mysidia + 3 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

gourabinda + 0 comments whats that String builder means?

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 + 1 comment 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(); } }

Pricks_123 + 0 comments Thanks #sharmatushar124 for ur Soln.

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

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 + 2 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 Great explanation. Thank you so much.

ParthHingorani + 0 comments The value of 'b x 2^j' gets added to 'a' in that expression. It is like 'a = a + (b x 2^j)'. Hope this helps.

ahmetsalttarimci + 0 comments Yes, only exception that code will terminate is ; first input 0 Great code @rshaghoulian

deeppandey573 + 1 comment System.out.print(a + " ");......whats the meaning of this line?

jaga1234reddie + 0 comments (answer for ur question is if consider a =10 , that line prints a blank space for the value i.e., 10) 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 k =0; int r=0; int a = in.nextInt(); int b = in.nextInt(); int n = in.nextInt(); // System.out.println(a+" "+b+" "+n ); for (double j =0;j<n;j++){ r = r+(int)(Math.pow(2.0,j)*b); k=r+a; System.out.print(k+" "); } System.out.print("\n"); } in.close(); }`

}

ruchikakandpal21 + 1 comment I have written the same code but it's not working. Can you help

RodneyShag + 0 comments Sure. Try to compare your code to the code I have posted above to see what's different. Change 1 line at a time from your code to mine to see when it starts working.

wobadha + 0 comments [deleted]kalyankumar11311 + 1 comment can u explain this code

RodneyShag + 0 comments Hi. We want to print each term in the formula provided in the problem description. This is the code that does so:

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

Try to compare the value of

**a**in my code above to each term in the equation in the problem statement. First, for j= 0, we will get:a + (2^0)*b

which matches the first term in the formula in the problem statement.

Try to see what we get for j=1 and j=2.

nburose91 + 0 comments While I agree this works, not sure if this is what was intended from the prompt. In the last section it describes: "Once we hit n=10, we print the first ten terms as a single line of space-separated integers.", which would imply that they want you to do the entire series calculation first, then print the result.

Seems a bit weird that this is where it is in the challenge list, as I would think a recursive solution is called for in that case.

Apoorvsh + 1 comment Why is a System.out.println(); added in the last. If I am remove it the code is not working. please help.

Sowmeya + 1 comment System.out.println(); What is the use of this?

RodneyShag + 0 comments This was answered in the post above you by Apporvsh. It makes the next print start on the next line.

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

rajeshrakesh5267 + 1 comment for(int j=0;j

`explain this logic`

shanibhati17 + 0 comments for(int i=0;i0){ res=(int)(res+Math.pow(2,j)*b); } System.out.printf("%d ",res); } System.out.printf("\n"); } } }

CloveJL + 0 comments pretty smart.

weichin092 + 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<t;i++){ int a = in.nextInt(); int b = in.nextInt(); int n = in.nextInt(); int temp= a; for (int j = 0; j < n; j++) { if (j == 0){ temp += b; }else{ temp += (int) (Math.pow(2.0, j) * b); } if(j!=n-1){ System.out.print(temp+ " "); }else{ System.out.print(temp+" \n"); } } } in.close(); }`

}

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

itstud87 + 2 comments Hello can you explain me in this case the logic of action for loop (j) and for loop (k)? Thank you.

RangelMX + 0 comments Excuse me, it wasn't optimal, but I corrected it.

https://www.dropbox.com/s/wsg7kacoquvopsv/Algoritmo.jpeg?dl=0

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

dhruvilshah35 + 2 comments It is an anwer I guess.Hope you find it good.

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(); for(i=0;i<n;i++) { a=a+(int) (Math.pow(2,i)*b); System.out.print(a+" "); } System.out.println(); i=0; } in.close(); } }

15n_j + 1 comment If I remove the i=0 code why does the output fall short?

dhruvilshah35 + 1 comment for second case you must need i=0 because for case 1 i incremented to n-1. or you can change j instead of i in inner for loop.So you you dont need to write i=0

15n_j + 0 comments Understood! thank you for the reply

sherzodkh + 0 comments perfect

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

mrinaldenre + 0 comments

Sort 986 Discussions, By:

Please Login in order to post a comment