Alex Sorkin - 3 months ago 23

C Question

So, for my assignment, I'm supposed to code a function that takes 2 unsigned arguments and outputs their product.

`unsigned multiply( unsigned a, unsigned b );`

For instance,

`multiply(3, 4)`

should return 12

The thing is, I'm not allowed to use +, -, /, *, or % operators. I'm only allowed to call functions, and increment/decrement with ++ and --.

I have another function already made to add 2 arguments:

`unsigned add(unsigned a, unsigned b)`

{

if (a > 0)

add(--a, ++b);

else return(b);

}

and I'm allowed to call this, along with any helper functions I need.

I've spent the past 30 minutes trying out various permutations but I just cannot get the math right; the closest I've come is getting b to double itself a times, but that's not going to cut it. Any ideas?

Edit: Forgot to mention! For/while loops aren't allowed either

Answer

```
unsigned add(unsigned a, unsigned b){
if (a > 0)
return add(--a, ++b);
else
return b;
}
unsigned multiply( unsigned a, unsigned b ){
if( a > 0)
return add(b, multiply(--a, b));
else
return 0;
}
```