program without using mathamatical operators

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sekhar_ps
    New Member
    • Jun 2006
    • 28

    program without using mathamatical operators

    how would you print 2 powers series from 0 to 100 (like pow(2,0),pow(2, 1).........pow( 2,100)) with out using mathematical operators
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    I wouldn't seems like a pointless exersise to me, however if you must then you need to specifiy exactly which operators and forbidden. What you the bitwise operators?

    Comment

    • sekhar_ps
      New Member
      • Jun 2006
      • 28

      #3
      hi,
      thanx for the reply,what iam saying is with out using mathematical operators not bitwise operators.

      Comment

      • D_C
        Contributor
        • Jun 2006
        • 293

        #4
        One problem you may run into is overflow. In this example, it prints 2^29, but not 2^30. Integers are 32-bit numbers, the most significant is reserved for the sign. If we include 2^30 in the loop, we shift it, 2^31 becomes a negative number, and the loop is still valid. One could always test while(number != (1<<31)). However, if the loop keeps going, since integers are typically 32-bit, (1 << 32) = 0 because the 1 overflows and is lost.

        Code:
        int main()
        {
          int number = 1; // assume 32-bit.
          while(number != (1 << 31)) // logical shift left, bitwise operator
          {
            cout << number << endl;
            number = (number << 1);
          }
              system("PAUSE");
              return 0;
        }
        Last edited by D_C; Jun 25 '06, 09:41 PM. Reason: message posted before I was finished

        Comment

        • Banfa
          Recognized Expert Expert
          • Feb 2006
          • 9067

          #5
          You should be careful using signed values in shift operations, particularly the right shift operation on a signed value is either undefined behaviour or implementation defined behaviour.

          I normally try to stick to unsigned variables when using shift operators as the results are more consistent cross platform.

          If you are using unsigned values you can then use 0 as the end condition of the loop

          Code:
          int main()
          {
              unsigned int number; // assume 32-bit.
          
              for(number=1; number != 0; number <<= 1)
              {
                  cout << number << endl;
              }
              system("PAUSE");
              return 0;
          }
          Unfortunately this doesn't get you to the 100th power and the shift operators do not work on floating point types.

          Comment

          Working...