Java Loops II

  • + 5 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");
    
    • + 2 comments

      what does this line(result += (1<< h) * b) do? what is the role of << operator?

      • + 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.

        • + 0 comments

          thankyou..

        • + 0 comments

          nice idea with the binary shift!

      • + 0 comments

        << is the bitwise left shift operator.

        1 << h takes the bits in 1 and shifts them with h positions to the left.

        1 << 0 == 1 1 << 1 == 2 1 << 2 == 4

    • + 0 comments

      for(int i=0;i

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

      Should be h<=x+1

    • + 0 comments

      best Answer Yet!

    • + 1 comment

      Why did you represent another variable result? Is it impossible if a is directly call in the for loop of shifting?

      • + 1 comment

        What does result do?

        • + 0 comments

          well doing so increases the looping hence it may cause time complexity issues (takes longer time ) hence to reduce that its easy to define another variable and assign it a value hence makes the process easy as looping tend to take much time to compile hence this shortens the time .