"Witless" <go******@hotmail.com> wrote in message
news:68**************************@posting.google.c om...
This is 'supposed' to be a simple problem and shouldn't need too much
time to solve :S
Below is a function that works like this:
int fn(int input)
{
int x=(input/8);
if(x%2)
x= x*8 + 8;
else
x = x*8;
return x;
}
A compiler must preserve the literal semantics of signed division. Presumably, your
assignment must do the same.
Input -> Output
===========
0..7 -> 0
8..15 -> 16
16..23 -> 16
24..31 -> 32
32..39 -> 32
40..47 -> 48
48..56 -> 48
You haven't said whether this is the entire input range, or merely a sample. That would
dramatically effect the answer.
Problem:
See if you can come up with a more efficient solution that can do it
without any division or multiplication operations.
Chances are, the compiler already does that. Hence Ben's comments.
Hint:
Think about what the numbers look like in binary.
Which is fine if input is always non-negative. It's not so simple for negative input in
which case the value bits could be just about anything under C90. Even under C99 there are
three varieties of negative integer representations. Under C90 there are also two classes
of division when one of the operands is negative!
If you have no time to look at it, let me know ASAP.
[If we didn't have time to look at it, why would we have the time to let you know ASAP
(sic)?]
The nearest ISO C solution I can think of is...
#include <limits.h>
int fn(int input)
{
if (input >= 0)
return input - (input & 7) + (input & 8);
if (INT_MIN + 1 == -INT_MAX && input == INT_MIN)
return INT_MIN;
if (-7 / 8 < 0)
{
input = -1-input;
return -input + (input & 7) - (input & 8);
}
return input + (-input & 15);
}
This still has a compile time test for the class of division which a C90 implementation
might use. I can't see a way around that without using / or %. Note that it's not obvious
that this is a more efficient solution!
Of course, if you make the input an unsigned int, the solution is trivial as Jack has
mentioned.
--
Peter