Hi, there is a good division and multiplication method by using shifting.
Lets take an example 833794 and divide this number by 10, shift this number to right only once: 83379, and if you want to divide by 100 shift this number to right twice:
8337. The same method is validate also for multiplication with only a little bit change, that is, only shift to left.
Now lets do some exercises :)
Q.1.)Given a numbers x and n, where n is a power of 2, write C code, which
gives the multiple of n which is greater than or equal to x.
ex :
I/P: 13 8
O/P: 16
I/P: 17 16
O/P: 32
The challenge: Do not use division or modulo operator.
unsigned int getBiggerPowerOf2( unsigned int x, unsigned int n ) {
if ( n == 0 ) return 0;
while ( n < x ) {
n = n << 1;
}
return n;
}
Q.2.)Write a C function, which takes a number n and positions p1 and p2 and returns if the the bits at positions p1 and p2 are set or not.
bool isBitsSet( int num, int p1, int p2 ) {
int temp = 0;
temp = ( 1 << (p1 - 1) ) + ( 1 << (p2 - 1) );
num = num & temp;
if ( num == temp ) return true;
return false;
}
Q.3.)Write a C function, which takes a number n and positions p1 and p2 and returns if the the bits at positions p1 and p2 are same or not.
bool isSameBits( int num, int p1, int p2 ) {
int temp = num;
temp = 1 & ( temp >> (p1 - 1) );
num = 1 & ( num >> (p2 - 1) );
return ( temp == num );
}
Q.4.) Give a fast way to multiply a number by 7.
number * 8 = number << 3;
number = ( number << 3 ) - number;
No comments:
Post a Comment