How to perform multiplication using only additions and assignments?

How to change the next program so that it performs the same task, but using only additions and appointments?

I can only make max 27 additions, and Output should be generated in one input. Cycles and other control flow operations not allowed

#include <iostream>

int main()
{
    int a;
    std::cout << "Enter number: ";
    std::cin >> a;

    std::cout << a*29 << std::endl;

    return 0;
}
+4
source share
9 answers

Another approach requiring 7 +:

int M1  = a;        // 1a
int M2  = M1 + M1;  // 2a
int M4  = M2 + M2;  // 4a
int M8  = M4 + M4;  // 8a
int M16 = M8 + M8;  // 16a
int res = M16 + M8 + M4 + M1; // 29a

The result is built from a binary multiplier pattern, that is, 29 decimal numbers is binary code 0001.1101. Therefore, we need to add M16, M8, M4 and M1 (and exclude M2).

+7
source

This is not general, and this cannot be, but to multiply by only 29 you can do this:

// x is input
int t = x;  // x*1
x = x + x;
x = x + x;
t = t + x;  // x*5
x = x + x;
t = t + x;  // x*13
x = x + x;
t = t + x;  // x*29

, , . t 29.

+6

21 .

#include <iostream>

int main()
{
    int a;
    std::cout << "Enter number: ";
    std::cin >> a;
    int b = (a+a+...+a) // 10 times
    b = b + b;
    b = b + (a + a + a ... + a ); // 9 times
    std::cout << b << std::endl;

    return 0;
}
+2

var?

b = a + a + a//3 times a 
b = b + b + b//9 times a
b = b + b + b//27 times a
b = b + a + a//29 times a
+2

- . . , ? ! for.

, :

  • for
  • sum

:

// get input
int input;
std::cout << "Enter number: ";
std::cin >> input;

// use a for loop to perform the addition
int sum = 0;
for(int i = 0; i< 29; ++i)
    sum += a;

// output result
std::cout << sum << std::endl;
+1

resRepetitive - -

a n . for/while

#include <iostream>

int main()
{
    int a,i,temp=0;
    std::cout << "Enter number: ";
    std::cin >> a;
    for(i=1;i<=29;i++)
        temp+=a;//add a repeatedly for 'n' number of times. Here 29 as per your requirement. a*n  
    std::cout << temp <<std::endl; 
    return 0;
}

int b=0,result=0;
b=a+a+a+a+a+a+a;\\adding for 7 times
result=b+b+b+b+a;\\4 times 7 (of a)= 28+a= 29 times (of a).

10 .

0

+ =, , , , undefined -

... + (a += ...) + ...

... - a +. , (a += ...) a .

, , , ++, += + . .

. https://ideone.com/fC3fai, ,

(a + a + a + a + a + (a += a + a + a) + a + a + a + a + a)

( ). ( , Java, ).

0

-

b = a + a + a + a + a + a + a + a + a + a + a + a + a + a + a; // equivalent to a*15

b += b -a;
0

:

int sum=0;
for(int i=0; i<multipler; i++){
    sum+=a; //adds value of a to itself
}
return sum;

2, :

a = a << 1;
-1

Source: https://habr.com/ru/post/1686191/


All Articles