you can do screwy things to avoid if statements. This is occasionally a performance tweak, depending on the code.
for example, say you wanted to set x to 12.34 if something is false, else set it to 56.78
double tf[] = {12.34, 56.78};
result = tf[(int)(boolean condition here)];
result = tf[(int)(x<y)]; //concrete example
this works because the condition returns 0 or 1, for false / true.
that is not how to solve THIS problem. Its just some ammo for the future.
this problem is trying to get you to re-invent a classic algorithm. If you still do not see it, ask again.. the above is the hint..
in action, this is an integer power function that avoids if/else to multiply by 1 (do nothing) or by p depending on if that bit was set.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
inline long long ipow(long long p, unsigned long long e) //fast for big powers (> 8)
{
const long long one = 1;
const long long *lut[2] = {&p,&one};
register long long result = 1;
result *= lut[!(e&1)][0]; p *= p;
result *= lut[!(e&2)][0]; p *= p;
result *= lut[!(e&4)][0]; p *= p;
result *= lut[!(e&8)][0]; p *= p;
result *= lut[!(e&16)][0]; p *= p;
result *= lut[!(e&32)][0]; p *= p;
result *= lut[!(e&64)][0];
return result;
}
|