使用增量进行乘法运算

时间:2014-09-18 08:29:24

标签: java recursion increment

我的任务是编写一个递归函数,将两个数相乘,只使用加法函数++--。我的附加功能是:

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

到目前为止,我的乘法功能是:

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

我不确定要放入peanotimes函数的第一个参数。现在问题是我将数字翻倍,而不是将其添加到原始数字。我知道我需要维护x变量,以便递归调用可以继续添加原始数字(而不是每次都加倍),但那么我实际上会在哪里添加数字?

我发现this与我的问题非常相似,但即使有这些提示,我也无法找到解决方案。

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

此版本最接近x * S(y) = x + (x * y)

的正式Peano公理
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));
    }
}
相关问题