Multiply by seven

I was asked this question: what is the fastest way to multiply a number by 7. She told me not to use any operators + , - , * , /. In tension, I could not answer the question.

I know that the fastest way to multiply a number by 8 is n<<3 but can it n*7be achieved?

+5
source share
11 answers
n*7 == (n<<3) - n

Not sure if this will be better than normal multiplication by 7, although

+5
source

Assuming that your compiler is not terrible n*7.

+12
source

:)

#include <stdio.h>

int mult7(int i)
{
    int res;
    __asm__("imull  $7, %1, %0" : "=r" (res) : "r" (i));
    return res;
}

int main()
{
    printf("%d", mult7(12)); //output: 84
    return 0;
}
+10

(+, -, * /):)

/* multiply by 7 without using the forbidden operators */
/* if `n` is larger than `INT_MAX / 7`
** or smaller than `INT_MIN / 7`
** the behaviour is undefined. */
int mult7(int n) {
  int n7 = n;
  n7 *= 7;
  return n7;
}
+7

-

a) n*7

-, .

b) the interviewer has a poor understanding of modern optimizing compilers

, , , ) , , , , .: -/

+5

, , "+" . - :


int add(int x, int y) {
  int a, b;
  do {
    a = x & y; b = x ^ y; x = a &lt&lt 1; y = b;
  }while(a);
  return b;
}

n, n < 1, n < 2.

"+" while, "-" while ( , ), (n < < < 3) - n.

: HTTP://geeki.wordpress.com/2007/12/12/adding-two-numbers-with-bitwise-and-shift-operators/

+5

,

n*7

(n<<3) - n
+2

, : pow(10, log10(n) + log10(7))

+2

, !

= (n < 3-n)

= n * 8 - n

= n (8 - 1)

= n * 7

+1

, " ", , :

int ans = (num<<2) + (num<<1) + num;

, , .

+1
int main()
   {
        int i;
        int x;
        int n;
        x = n;
        for (i = 2; i < 8; i++)
        {
             n += x;
        }
        return 0;
    }

EDIT: c ( ) , . = c, + =. , + , .

I know that he uses ++, but this, of course, is not the same as "+" and. = avoids reservations.

0
source

All Articles