C++ Multiply without multiply

A couple of ways for write multiply, without using multiply…

int multiply(int value,int mul) {

int ret=0;

int mulabs = mul;
if(mulabs < 0) mulabs = 0 – mulabs;

for(int n=0;n<mulabs;n++) {
ret += value;
}

if(mul < 0) ret = 0-ret;

return ret;
}

int multiply2(int value,int mul) {

int total=0;

for(int n=30;n>=0;n–) {

if((mul & (1 << n)) > 0) {
total += value << n;
}
}
return total;

}

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>