By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,406 Members | 982 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,406 IT Pros & Developers. It's quick & easy.

program without using mathamatical operators

P: 28
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
Jun 22 '06 #1
Share this Question
Share on Google+
4 Replies


Banfa
Expert Mod 5K+
P: 8,916
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?
Jun 22 '06 #2

P: 28
hi,
thanx for the reply,what iam saying is with out using mathematical operators not bitwise operators.
Jun 25 '06 #3

100+
P: 293
D_C
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.

Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.   int number = 1; // assume 32-bit.
  4.   while(number != (1 << 31)) // logical shift left, bitwise operator
  5.   {
  6.     cout << number << endl;
  7.     number = (number << 1);
  8.   }
  9.       system("PAUSE");
  10.       return 0;
  11. }
Jun 25 '06 #4

Banfa
Expert Mod 5K+
P: 8,916
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

Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.     unsigned int number; // assume 32-bit.
  4.  
  5.     for(number=1; number != 0; number <<= 1)
  6.     {
  7.         cout << number << endl;
  8.     }
  9.     system("PAUSE");
  10.     return 0;
  11. }
Unfortunately this doesn't get you to the 100th power and the shift operators do not work on floating point types.
Jun 26 '06 #5

Post your reply

Sign in to post your reply or Sign up for a free account.