We're trying to sum up three ints using a single + operator. This is part of a task from a course at the university, so please don't post any actual code. We'd just like to have some input, maybe an idea that leads us in the right direction.
Basically we're given three ints and are supposed to return two, that when summed up by +, return the value that int1+int2+int3 would have returned. Of course we're not allowed to use - either. Just all of the other bitfield ops and !. We've already tried several "algorithms" that, unsurprisingly, didn't quite cut it
In any case, a few things we tried (feel free to laugh at any point...):
- We used
int1&int2 to find bits where both are 1, (where + would produce a carry bit), shift the result 1 up and merge (|) this with
(int1|int2). Return this as result1 and do the same for
int2&int3.
This yielded relatively good results. In most cases there was one carry bit too much in the final result. This is probably due to the way we try to find the carry bits. It's flawed as each carry bit changes the positions of the ones following. We didn't take this into account (and cannot, we're limited to 16 ops)
- Tried to construct result1 with
int1|(int2<<16) - in other words store int2 in the highword of our result. We then tried to construct result2 in a way that when summed up with result1, the effects of the shift cancel each other out. I guess it's appropriate to laugh at this point
Any suggestions? This part of the task doesn't give a lot of points, so it's supposed to be fairly easy when compared to something like log2(x) - which I found a lot easier than this one