#x86, 41 bytes
Mostly straightforward implementation of the formula with input in ecx
and output on the stack.
The interesting thing is that I used a cubing function, but since call label
is 5 bytes, I store the label's address and use the 2 byte call reg
. Also, since I'm pushing values in my function, I use a jmp
instead of ret
. It's very possible that being clever with a loop and the stack can avoid calling entirely.
I did not do any fancy tricks with cubing, like using (k+1)^3 = k^3 + 3k^2 + 3k + 1
.
.section .text
.globl main
main:
mov $10, %ecx # n = 10
start:
lea (cube),%edi # save function pointer
call *%edi # output n^3
sub %ecx, %eax # n^3 - n
xor %edx, %edx
push $6
pop %ebx # const 6
idiv %ebx # k = (n^3 - n)/6
mov %eax, %ecx # save k
call *%edi # output k^3
push %eax # output k^3
neg %ecx # -k
inc %ecx # -k+1
call *%edi # output (-k+1)^3
dec %ecx
dec %ecx # -k-1
call *%edi # output (-k-1)^3
ret
cube: # eax = ecx^3
pop %esi
mov %ecx, %eax
imul %ecx
imul %ecx
push %eax # output cube
jmp *%esi # ret
Objdump:
00000005 <start>:
5: 8d 3d 25 00 00 00 lea 0x25,%edi
b: ff d7 call *%edi
d: 29 c8 sub %ecx,%eax
f: 31 d2 xor %edx,%edx
11: 6a 06 push $0x6
13: 5b pop %ebx
14: f7 fb idiv %ebx
16: 89 c1 mov %eax,%ecx
18: ff d7 call *%edi
1a: 50 push %eax
1b: f7 d9 neg %ecx
1d: 41 inc %ecx
1e: ff d7 call *%edi
20: 49 dec %ecx
21: 49 dec %ecx
22: ff d7 call *%edi
24: c3 ret
00000025 <cube>:
25: 5e pop %esi
26: 89 c8 mov %ecx,%eax
28: f7 e9 imul %ecx
2a: f7 e9 imul %ecx
2c: 50 push %eax
2d: ff e6 jmp *%esi