多个2数的尾递归方法 [英] Tail recursive method to multiple 2 numbers

查看:42
本文介绍了多个2数的尾递归方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

多个2数的尾递归方法

public static int Multiply2(int x, int y)
{
    return MulTail(x, y, x);
}

public static int MulTail(int x, int y, int result)
{
    if (y == 0 || x == 0)
        return 0;
    if (y == 1)
        return result;

    return MulTail(x, y - 1, result+x);

}

更改了实现以适应负数

public static int Multiply2(int x, int y)
        {
            if ((y < 0 && x > 0) || (x < 0 && y < 0))
            {
                y = y - y - y;
                x = x - x - x;
            }


            return MulTail(x, y, x);
        }

        public static int MulTail(int x, int y, int result)
        {
            if (y == 0 || x == 0)
                return 0;
            if (y == 1)
                return result;

            return MulTail(x, y - 1, result+x);

        } 

推荐答案

一种仅使用加法、减法和加倍的乘法方法称为 古埃及乘法.此方法比您提出的方法更有效,并且可以制定为尾递归实现.

A method for multiplication using only addition, subtraction, and doubling is called Ancient Egyptian Multiplication. This method is more efficient than what you've proposed and can be formulated into a tail-recursive implementation.

这篇关于多个2数的尾递归方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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