# 以有效的方式乘以7[英] Multiply by 7 in efficient way

### 问题描述

```num = (num << 3) - num;
```

## 推荐答案

```7
```

7是7个倍数.回答您问的问题，但我敢肯定它不会回答您的意思是要问的问题.

```x * 7
```

(如果我是面试官，对问题的理解和理解比任何特定答案都给人留下了深刻的印象.)

## 其他推荐答案

```static unsigned int mult7[] = {0, 7, 14, 21, ...};
unsigned int three = 3;
unsigned int twenty_one = mult7[three];
```

(a)检查以下代码:

```#include <stdio.h>

static int mult7 (int num) {
return num * 7;
}

int main (int argc, char *argv[]) {
printf ("%d\n", mult7 (atoi (argv[1])));
return 0;
}
```

```_mult7:
pushl   %ebp             ; stack frame setup.
movl    %esp, %ebp
movl    8(%ebp), %edx    ; get value to edx
movl    %edx, %eax       ;    and eax.
sall    \$3, %eax         ; eax <- eax * 8.
subl    %edx, %eax       ; eax <- eax - edx.
popl    %ebp             ; stack frame teardown and return.
ret
```

at -O3(我喜欢称为疯狂的优化级别)，整个过程都将main与:

```call    _atoi
movl    \$LC0, (%esp)

leal    0(,%eax,8), %edx     ; these two are the relevant instructions.
subl    %eax, %edx

movl    %edx, 4(%esp)
call    _printf
```

```num *= 7;
```

.

## 其他推荐答案

```num = (num << 3) - num;
```

```int mul(int num)
{
return num * 7;
}
```

```Dump of assembler code for function mul:
0x00000000004004c4 <+0>:    push   rbp
0x00000000004004c5 <+1>:    mov    rbp,rsp
0x00000000004004c8 <+4>:    mov    DWORD PTR [rbp-0x4],0xa
0x00000000004004cf <+11>:   mov    edx,DWORD PTR [rbp-0x4]
0x00000000004004d2 <+14>:   mov    eax,edx
0x00000000004004d4 <+16>:   shl    eax,0x3
0x00000000004004d7 <+19>:   sub    eax,edx
0x00000000004004d9 <+21>:   mov    DWORD PTR [rbp-0x4],eax
0x00000000004004dc <+24>:   pop    rbp
0x00000000004004dd <+25>:   ret
End of assembler dump.
```

```Dump of assembler code for function mul:
0x00000000004004e0 <+0>: lea    eax,[rdi*8+0x0]
0x00000000004004e7 <+7>: sub    eax,edi
0x00000000004004e9 <+9>: ret
End of assembler dump.
```