Reputation: 1694
Hi this is an interview question.
For any given number calculate next number which is divisible by 8.
i.e. If given number is 43
, our algorithm should produce 48
as result. If number is already divisible by 8
it should say Number already divisible by 8
and produce next number divisible by 8.
I suggest them that any number which is divisible by 8
have last three bits as 0
(LSB+2,LSB+1,LSB). But I am not able to give exact solution.
What I said is right approach to solve this problem or we can go for some smarter solution? I need to do this with bit manipulation.
Upvotes: 0
Views: 2148
Reputation: 21
void main()
{
int n;
printf("\n Enter the number:");
scanf("%d",&n);
if(n==8 && n%8==0)
printf("%d it is already divisible by 8",n);
else
{
printf("not divsible by 8 so nearest number is:");
i=n/8;
i++;
n=i*8;
printf("%d is next number divisible by 8",n);
}
}
you can try this which is one of the solution
Thankyou.
Upvotes: 0
Reputation: 43487
It's easy with a while loop:
if number % 8 == 0
already divisible by 8
while number % 8 != 0
++number
This is O(1)
, since 8 is a constant, but we can do better with the following formula:
if number % 8 == 0
already divisible by 8
number = number + 8 - number % 8
Upvotes: 2
Reputation: 36349
You're on the right track.
int next8(int n) {
int bits = n & 7; // give us the distance to the previous 8
if (bits == 0) printf("Number already divisible by 8");
return n + (8-bits);
}
(Note: I hate it when functions that are supposed to be pure print something, but the task demands so. Sorry.)
Upvotes: 9
Reputation: 2865
Your check is correct, to check it you can perform a bitwise AND with 7 and make sure it is 0 (X & 7 == 0). To get the next number - Shift right by 3, add 1 and shift back ( ((X >> 3) + 1) << 3 )
Upvotes: 0