Write a program that reads an integer value from the keyboard into a variable of type int, and uses one of the bitwise operators (i.e. not the % operator!) to determine the positive remainder when divided by 8.
For example, 29 = (3×8)+5 and 14 = ( 2×8)+2 have positive remainder 5 and 2, respectively, when divided by 8.
I tried to search how can I solve it. What I did is to break given examples numbers into binary.
29 => 101001
8 => 001000
5 => 000101
I don’t know what is operation I should do with 29 and 8 to get result 5 in binary.
While searching there’s some guys said that we should do (& operation with 7 )
remainder = remainder & 7 ;
Then I tried to do this with Value itself
value = value & 7 ;
and Here’s my code After doing it …
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
int main()
{
int value = 0;
int divisor = 8;
int remainder = 0;
cout << "Enter an integr and I'll divide it by 8 and give you the remainder!"
<<endl;
cin >> value;
value = value & 7;
remainder = value & divisor;
cout << remainder;
return 0;
}
It gave me result 0 when I use value 29. I don’t know what I wrote was right or not.
Since 8 is exactly
2^3, the modulo-8 remainder of any number is composed of its last three binary digits, i. e. it equals the number bitwise-and 7:(7 is
111in binary, that’s why.)