Multiplication using increments

2019-08-31 08:04发布

问题:

My assignment is to write a recursive function to multiply two numbers together, using only an addition function, ++, and --. My addition function is:

public static int peanoplus(int x, int y) {
    if(y==0) return x;
    else return peanoplus(++x,--y);
}

What I have so far for my multiplication function is:

public static int peanotimes(int x, int y)
{
    if(y==0) return x;
    else return peanotimes(peanoplus(x,x),--y);
}

I am not exactly sure what to put in the first parameter for the peanotimes function. Right now the issue is that I'm doubling the number, rather than adding it to the original number. I know that I need to maintain the x variable so that the recursive calls can continue adding the original number (instead of doubling every time), but then where would I actually add the numbers?

I found this which is very similar to my question, but even with those tips I am unable to find a solution.

回答1:

if( y == 0 || x == 0 ) { return 0; }
    else { return peanoplus(x, peanotimes(x,--y)); }


回答2:

This version closest matches the formal Peano axiom of x * S(y) = x + (x * y)

public static int peanotimes(int x, int y)
{
    if (y == 0) {
        return 0;       // terminate recursion, NB: not "x"
    }  else {
        return peanoplus(x, peanotimes(x, --y));
    }
}