Multiplication using increments

为君一笑 提交于 2019-12-11 16:25:37

问题


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));
    }
}


来源:https://stackoverflow.com/questions/25907759/multiplication-using-increments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!