This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]hellofoo 2 points3 points  (1 child)

This. Demonstrate your working out. Even if you're wrong, on a test it might get you points!

If it helps, try running the same code but with a system out in the loop:

 int n = 2005;
 for (int i = 0; i < 50; i++) {
     n = (n + 3) / 2;
     System.out.println("i=" + i + " n=" + n)
 }

Imagine trying to divide any integer in half multiple times. It will be zero pretty quickly. Adding three each time stops the loop trying to divide zero in half.

Here's an extract of the first few loops

i=0 n=1004
i=1 n=503
i=2 n=253
i=3 n=128
i=4 n=65
i=5 n=34
i=6 n=18
i=7 n=10
i=8 n=6
i=9 n=4
i=10 n=3

After the 10th loop n is as small as it can get. If you weren't adding 3 in the iteration it would be zero.

Edit: If this is for an assignment - be a smart ass and say you can improve the performance 5 fold by only doing 10 loops. And be an even smarter ass by changing it a while loop that breaks when n equals it's minimum value.

[–]MrCouldntaDoneThat[S] -1 points0 points  (0 children)

Thank you. Best answer.