2

I need an algorithm to multiply two numbers without using the multiply (*) Operator and without using bitwise with complexity less than O(N) and I came up with the most obvious one which is

int m = 6, n = 5, sum = 0;
for(int i = 0, i<n, i++)
    sum += m;

but this is O(N) which won't work for me.

Mohamed Saleh
  • 135
  • 3
  • 14
  • Would `exp(log(m) + log(n))` be cheating? :p – Hong Ooi Nov 05 '15 at 14:56
  • 4
    What operations are allowed? Or perhaps the question should be why are their restrictions in place - eg is it that you are running this on hardware that doesn't do multiplications? Is it a homework assignment that forbids them? Something else? For example you can use logarithms to do multiplication without actually using multiplication but that might also be not good (I'm not sure what the Time complexity is for working out logs in a modern computer). – Chris Nov 05 '15 at 14:57
  • Can you use bitwise operators? – Giorgi Nakeuri Nov 05 '15 at 14:57
  • 2
    You can use bitwise multiplication here is a good example: http://stackoverflow.com/a/3722053/98491 – Jürgen Steinblock Nov 05 '15 at 14:58
  • @HongOoi yeah it would :D the purpose is not to solve the multiplication part the purpose it to find the most efficient solution – Mohamed Saleh Nov 05 '15 at 14:59
  • @Chris yeah it's a part of homework assignment and the code already detects the time complexity – Mohamed Saleh Nov 05 '15 at 15:00
  • 1
    What is `N` in this case? (Please augment the question in favour to commenting this comment.) (|m|+|n|? max(|m|, |n|)?) How about ((m+n)²-(m-n)²)/4 (/4 is not more complicated than general multiplication, it can be implemented by bit shifting. Squaring is less complicated than multiplication (consider look-up-tables for both), if not by much.) – greybeard Nov 05 '15 at 15:23
  • N, the input size, is different than the magnitude of the numbers. You only need `log M + log N` space to store the input, so repeated addition is actually exponential in the input size. – chepner Nov 05 '15 at 15:57
  • You can do long multiplication with pencil and paper, just write it down as an algorithm. – n. m. could be an AI Nov 05 '15 at 17:58
  • Possible duplicate of [How to perform multiplication, using bitwise operators?](http://stackoverflow.com/questions/3722004/how-to-perform-multiplication-using-bitwise-operators). One of the answers (http://stackoverflow.com/a/14663667/224132) has the exact algorithm needed to do the multiply in log N time. (left and right shifts, stopping when you've right-shifted all the bits out of the operand you're shifting.) – Peter Cordes Nov 05 '15 at 19:45
  • `multiply … without using the multiply (*) Operator and without using bitwise with complexity less than O(N)` - _bitwise_ is lacking a noun (and I'm still missing a definition of `N` - it is not `n` without you stating so). – greybeard Nov 07 '15 at 08:06

5 Answers5

2

I have following solution

public static int mult(int m, int n) {
        int amount = 1;
        int bSum = 0;
        int sum = 0;
        int current = m;
        while (bSum + amount <= n) { 
            sum += current;
            current = current + current;
            bSum += amount;
            amount = amount + amount;
        }
        // bSum = 1+2+4+ ... + 2^k = 2^(k+1) - 1
        // cycle pass log(n) times

        if (bSum < n) {
            sum += mult(m, n - bSum); // n - bSum less n/2
        }
        return sum;
    }

The complexity is O(log(n)+log(n/2)+log(n/4) + ...) = O(log(n)+log(n) - log(2) + log(n) - log(4)). Total number of log (n) in sum is O(log(n)). From this final complexity of solution O(log^2(n)).

Alexander Kuznetsov
  • 3,062
  • 2
  • 25
  • 29
2

Thank you guys i have figured a simple solution:

static ulong Mul(uint N, uint M)
    {   if (N == 0)
            return 0;
        if (N == 1)
            return M;
        ulong res;
        res = Mul(N / 2, M);
        if (N % 2 == 0)
            return res+res;
        else
            return res+res+M;
        }
Mohamed Saleh
  • 135
  • 3
  • 14
  • 1
    Just so you're aware, `N/2` is the same as `N>>1`, and `N%2` is the same as `N&1`. So you're still using bitwise operations, just hiding the fact. – Teepeemm Nov 06 '15 at 21:46
  • @Teepeemm well i don't understand the bitwise operations but i understand this simple algorithm :D – Mohamed Saleh Nov 06 '15 at 21:54
  • Point is, a right shift by one is the same as division by 2. If you do `16 >> 1`, you will get `8`. Similar for `N%2` being the same as `N&1`. So while you may understand this approach better (we all do), it is still doing the same thing. – Zabuzard Feb 13 '20 at 01:40
0

Here's a recursive solution in Python:

import math
def fast_multiply(m, n):
    if n == 0: return 0
    shift_by = len("{0:b}".format(n)) - 1
    remainder = n - (1 << shift_by)
    return (m << shift_by) + fast_multiply(m, remainder)

This runs in O(log(n)) because you'll have at most log(n) levels in the recursion tree, with only one recursive call, and O(1) work outside of the recursive calls.

slider
  • 12,810
  • 1
  • 26
  • 42
0

It's iteration please see the link for explanation.

def multiply(x, y):
    if y < 0:
        return -multiply(x, -y)
    elif y == 0:
        return 0
    elif y == 1:
        return x
    else:
        return x + multiply(x, y - 1)

Here is the link that explain step by step also the Visualize Python code execution that you can see each step until get the output

Kate Kiatsiri
  • 63
  • 2
  • 7
  • 1
    Can you explain your solution? – AMC Feb 13 '20 at 02:12
  • While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn, and apply that knowledge to their own code. You are also likely to have positive feedback from users in the form of upvotes, when the code is explained. – borchvm Feb 13 '20 at 06:28
  • With some number pairs as input it throws `RecursionError: maximum recursion depth exceeded in comparison` – karel Feb 13 '20 at 07:27
  • just added the link for flowchart and visualization step by step from the site hope it helps. – Kate Kiatsiri Feb 14 '20 at 04:45
0
#include <bits/stdc++.h>
  
using namespace std;

int multiply(int a,int b)
{
  int temp;
  if( a == 0){

     return 0;

  }

  if( a == 1){

     return b;

   }

   temp = multiply(a/2, b);

   if (a % 2 == 0){

      return temp + temp;

   }

   else{

       return temp+temp+b;

     }
   }

 int main(){

 int a,b;

 cin>>a>>b;
 cout<<multiply(a,b)<<endl;

 return 0;
 }