3 ms·
Yeah, you're right. I had some more time to think, here's an updated, clearer version. I really really hate how you HAVE to define the last loop as 0 -> INT_MIN
by anonymous 13y ago
Yeah, you're right. I had some more time to think, here's an updated, clearer version. I really really hate how you HAVE to define the last loop as 0 -> INT_MIN + 1 -> INT_MIN -> INT_MAX -> 0. And there's no way to do it other than to use ifs. And there's no getting around that f(f(0)) != 0 (if you want the function to be correct in the most possible cases, that is). If you remove the ifs, it fails for INT_MAX, -INT_MAX and 0. Ifs in numeric code always make me uneasy.
/*
* f(f(n)) = -n
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
int32_t f(int32_t n) {
if (n == 0) {
return -0x7fffffffL;
}
if (n == -0x7fffffffL) {
return n-1;
}
if (n == -0x80000000L) {
return 0x7fffffffL;
}
if (n == 0x7fffffffL) {
return 0;
}
int32_t s = 1 - 2 * ((uint32_t)n >> 31);
int32_t m = 2 * (n & 1) - 1;
return m * n + s;
}
int main(int argc, char** argv) {
int32_t n[] = { 1, 2, 3, -1, -2, -3, 0, 5, 6, 10, 20, 50, 0x7fffffff, 0x80000000, -0x7fffffff };
int count = sizeof(n) / sizeof(int32_t);
for (int i = 0; i < count; i++) {
printf(" f(%d) = %d\n f(f(%d)) = %d\n", n[i], f(n[i]), n[i], f(f(n[i])));
}
}