# 设计函数f（f（n））== -n

2019/12/17 21:34

``f(f(n)) == -n``

### #1楼

x86 asm（AT＆T风格）：

``````; input %edi
; output %eax
; clobbered regs: %ecx, %edx
f:
testl   %edi, %edi
je  .zero

movl    %edi, %eax
movl    \$1, %ecx
movl    %edi, %edx
andl    \$1, %eax
subl    %eax, %ecx
xorl    %eax, %eax
testl   %edi, %edi
setg    %al
shrl    \$31, %edx
subl    %edx, %eax
imull   %ecx, %eax
subl    %eax, %edi
movl    %edi, %eax
imull   %ecx, %eax
.zero:
xorl    %eax, %eax
ret
``````

### #2楼

``````sub f {
my \$n = shift; return ref(\$n) ? -\$\$n : \\$n; } ``````

``print \$_, ' ', f(f(\$_)), "\n" for -2, 0, 1, 1.1, -3.3, 'foo' '-bar'; ``

``````-2 2
0 0
1 -1 1.1 -1.1 -3.3 3.3 foo -foo -bar +bar ``````

### #3楼

``````def f(x):
if type(x) == list: return -x[0] return [x] f(2) => [2] f(f(2)) => -2 ``````

### #4楼

（1849436465 2 +1）mod（2 32 -3）= 0。

``````def mods(x, n):
y = x % n
if y > n/2: y-= n return y ``````

``````def f(x):
return mods(x*1849436465, 2**32-3) ``````

### #5楼

``````function f(n) {
try { return n(); } catch(e) { return function() { return -n; }; } } ``````

`f(f(0)) => 0`

`f(f(1)) => -1`

0
0 收藏

0 评论
0 收藏
0