4 ms·
Source: /* * f(f(n)) = -n */ #include <stdlib.h> #include <stdio.h> #include <stdint.h> int32_t f(int32_t n) { retu
by anonymous 13y ago
Source:
/*
* f(f(n)) = -n
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
int32_t f(int32_t n) {
return (2 * (n & 1) - 1) * n + (2 * ((n & 1) & ((n >> 31) & 1)) - 1);
}
int main(int argc, char** argv) {
int32_t n[] = { 1, 2, 3, -1, -2, -3, 0, 5, 6, 10, 20, 50, 0x7fffffff, 0x80000000 };
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])));
}
}
Result:
f(1) = 0
f(f(1)) = -1
f(2) = -3
f(f(2)) = -2
f(3) = 2
f(f(3)) = -3
f(-1) = 0
f(f(-1)) = -1
f(-2) = 1
f(f(-2)) = 0
f(-3) = -2
f(f(-3)) = 1
f(0) = -1
f(f(0)) = 0
f(5) = 4
f(f(5)) = -5
f(6) = -7
f(f(6)) = -6
f(10) = -11
f(f(10)) = -10
f(20) = -21
f(f(20)) = -20
f(50) = -51
f(f(50)) = -50
f(2147483647) = 2147483646
f(f(2147483647)) = -2147483647
f(-2147483648) = 2147483647
f(f(-2147483648)) = 2147483646
- wrboyce 13y agoSomething looks wrong here… f(-1) = 0 f(0) = -1 f(f(-1)) = -1 Your code doesn't seem to handle the f(f(-n)) == n case
- anonymous 13y agoYeah, 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]))); } }