递归函数将数字除以2而不使用/ [英] Recursive function that divides the number by 2 without using /

查看:129
本文介绍了递归函数将数字除以2而不使用/的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助。
我需要创建一个递归函数,它接收一个n数字并返回n / 2而不分割。

编辑:

这是我写的,但它只有在分割后仍然是十进制数,而不是一个浮点数,这就是为什么我问。

  int递归(int a,int b)
{
if(a ==(0.5 * b))
return a;

返回递归(a-1,b);
}


解决方案

递归解决方案要慢得多,但是这里有一个使用python 3的正整数实现。如果a $ b

  def divRecursive(a,b):

return 0
return 1 + divRecursive(ab,b)


I need help. I need to create a recursive function that receives a "n" number and returns "n/2" without dividing.

Edit :

This is what I wrote, but it works only if after dividing it will still be a decimal number and not a float, that's why I asked.

int recursive(int a, int b)
{ 
  if ( a == (0.5 * b) )
    return a;

  return recursive(a-1, b);
}

解决方案

Recursive solutions are much slower, but here's an implementation for positive integers using python 3

def divRecursive(a,b):
    if a<b:
        return 0
    return 1+divRecursive(a-b,b)

这篇关于递归函数将数字除以2而不使用/的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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