Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added very easy, short, super fast method #55

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,40 +1,27 @@
/*
* Author: Madhur Chauhan
* A simple log(min(a,b)) solution, but does not take more than 96 instructions
* Similar to binary exponentiation by exploiting bit pattern of multiplicand
*/
#include <vector>
#include <iostream>
using namespace std;

int multiply(int a, int b, vector<int>& dp)
{
int bigger = a < b ? b:a;
int smaller = a <b ? a:b;

if (smaller==0)
return 0;

if (smaller==1)
return bigger;

if (dp[smaller]!=-1)
return dp[smaller];

int s = smaller >> 1; //divide by 2

int side1 = multiply(s,bigger,dp);
int side2 = 0;
if (smaller%2)
side2 = side1+bigger;
else
side2 = side1;

dp[smaller] = side2 +side1;
return side1+side2;
}
auto multiply=[](int a, int b){
int big=a>b?a:b, small=a<b?a:b, res=0;
while(small){
if(small&1) res+=big;
big<<=1, small>>=1;
}
return res;
};

int main()
{
int m = 7, n = 6;
int smaller = m>n?n:m;
int bigger = m>n?m:n;
std::vector<int> dp(smaller+1,-1);

cout<<multiply(smaller,bigger,dp)<<endl;
return 0;
}