使用增量相乘 [英] Multiplication using increments

查看:98
本文介绍了使用增量相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

推荐答案

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

这篇关于使用增量相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆