使用递归编码整数乘法函数(在C中)

时间:2009-11-22 18:08:24

标签: c recursion

有人能告诉我如何使用递归编写乘法函数(在C中)?

10 个答案:

答案 0 :(得分:9)

好的,我们是原创的。 :)

unsigned int mul(unsigned int a, unsigned int b)
{
    if ( !a || !b ) return 0;
    if ( a == 1 ) return b;
    if ( b == 1 ) return a;

    return mul(a-1, b-1)+a+b-1;
}

答案 1 :(得分:9)

如果你真的想给同龄人和你的老师留下深刻的印象,请提交一下 - 这既是递归又快速的!

int mul(int a, int b)
{
    if ( a < 0 ) return -mul(-a,b);
    if ( b < 0 ) return -mul(a,-b);
    if ( b == 0 ) return 0;
    return (mul(a,b>>1)<<1)+(b&1?a:0);
}

已添加:作为额外奖励,这可正确处理正值,负值和0值。

答案 2 :(得分:5)

这是功能:

int mulitplication(x,y)
{
    if (y==0)
    {
      return 0;
    }
    else
      return x+multiplication(x,y-1);
    }
}

答案 3 :(得分:3)

如果你需要很好的帮助,你必须更加具体。但这里是C中的递归函数,它将两个正整数相乘:

int multiply(int multiplicand, int multiplier)
{
  if(multiplier == 0)
  {
    return 0;
  }
  return multiply(multiplicand, multiplier - 1) + multiplicand;
}
  

Jonathan Leffler写道:如果乘数为负数?

确定:

int multiply(int multiplicand, int multiplier)
{
  if(multiplier == 0)
  {
    return 0;
  }
  if(multiplier < 0)
  {
    return multiply(multiplicand, multiplier + 1) - multiplicand; //Edit: changed "+ multiplicand" to "- multplicand"
  }
  return multiply(multiplicand, multiplier - 1) + multiplicand;
}
  

Mark Byers写道:负面版本仍然是错误的。

抱怨道,抱怨道。为我提供从记忆中书写而无需测试的权利。这个测试了许多整数范围,负面和正面,奇数和偶数。应该适用于任何整数值。风流Wintereenmas。

答案 4 :(得分:2)

一遍又一遍地添加它自己N次。也就是说,如果你想将数字乘以N ..

答案 5 :(得分:2)

替代版本:

int mulInner(int a, int b, int c)
{
    if (b == 0)
        return a*c;
    return mulInner(a, b-1, c+1);
}
int mul(int a, int b)
{
    return multInner(a, b, 0);
}

嘿,他没有说不使用operator* ......

答案 6 :(得分:2)

这仅在第一个操作数大于零时有效,但至少它很短且令人困惑。 ;)

int mul(int a, int b) {
  return b + (--a ? mul(a, b) : 0);
}

但是,我不确定评估顺序是否已定义,因此您可能必须将减量移到表达式之外:

int mul(int a, int b) {
  a--;
  return b + (a ? mul(a, b) : 0);
}

答案 7 :(得分:1)

如果我没错,是这样的......

int mul(int a, int b)
{
if(b==1)
return a;
else
return a+mul(a,b-1);
}

答案 8 :(得分:1)

int mul(int a,int b)
{
     if(b==1)
        return a;
     else
        return(a+(mul(a,b-1)));
}

答案 9 :(得分:0)

50个字符:

m(x,y){return!y?0:rand()%2?m(x,y+1)-x:m(x,y-1)+x;}

我希望我使用rand()函数(特别是以这种方式)得分,以及一般语法细节。根据您的系统库和月亮的相位,请注意递归可能导致高参数值的段错误,例如计算2 × 3