Question

I need to create a recursive function that receives a number by two without using /.

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

Btw, the function can receive only 1 parameter not 2 or more :/

Was it helpful?

Solution 3

You can try this, it should work:

int dividebytwo (int a){
    static int answer = 0;

    if (a < 0){
        if ((answer * 2) > a){
            answer --;
            return dividebytwo (a);
        }

        return answer;

    } else if (a > 0){
        if ((answer * 2) < a){
            answer ++;
            return dividebytwo (a);
        }

        return answer;
    }

    return 0;
}

The trick here is using the static attribute. The static attribute means that the variable is only initialized once and retains its value after every function call. Really, you're using two parameters but it looks like you're only using one.

The only downside to this function is that you can only count on it to work more than once. Since this is probably for a simple homework assignment, it probably doesn't matter. But in reality, this is considered hugely inefficient and unreliable.

To compensate for the only-works-once factor, may add one of these fixes:

  • declare answer as a global variable and set it to 0 before every function call.

  • append return answer = 0; to the end of the function, instead of return 0;. This is so that whenever you want to call it again, you would call it beforehand as dividebytwo (0);.

I also cannot stress enough how weird of a concept this is, it sets of all sorts of red flags for anyone who practices careful programming - could be why you're getting so many downvotes. So use with caution!

OTHER TIPS

I think you need something like this

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

This divides by two using repeated subtraction and recursion.

int divide_by_two(int a) {
    if (a < 0) return -divide_by_two(-a);
    if (a < 2) return 0;
    return 1 + divide_by_two(a - 2);
}

Generalising, this divides a by b using repeated subtraction and recursion.

int divide(int a, int b) {
    if (a < 0) return -divide(-a, b);
    if (b < 0) return -divide(a, -b);
    if (a < b) return 0;
    return 1 + divide(a - b, b);
}

Note, these functions don't round exactly the same way that division is defined to do in C.

#include<stdio.h>
int divide(int a, int b){
    if( a-b < 0)
      return 0;
    else if ( a-b == 0)
      return 1;
    else {
      return divide(a-b, b) + 1;
    }
  }

http://codepad.org/o4CoiaON

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top