Home > Net >  Getting the number factors of 2 in the given value using recursion
Getting the number factors of 2 in the given value using recursion

Time:11-28

I'm trying to make a program where a method takes a single positive integer as its argument and returns the number of factors of 2 in the number, an example being numbers that are twice an odd number returns one, numbers that are four times an odd returns two, etc.

  public int twos(int n){
    int twos=0;
    if(n%2!=0){
      return(0);
    }
    if(n/3>=1){
      System.out.println("\n" n);;
     return twos(n/3) 1;
    }
    else{
      return(0);
    }
   // return(twos);
  }

The code I have above only works for the integers 6 and 12, but not for all integers. How would you make this work for all digits?

CodePudding user response:

While creating a recursive implementation, you need always define Base case and Recursive case (every recursive method would contain these two parts, either implicitly or explicitly).

  • Base case - represents a condition (or group of conditions) under which recursion should terminate. The result for base case is trivial and known in advance. For this task, Base case is when the number is not even, return value is 0.

  • Recursive case - is the place where the main logic of the recursive method resides and where recursive calls are made. In the Recursive case we need to perform a recursive call with n / 2 passed as an argument, and return the result of this call 1 (because the received argument is even, and we need to add one power of 2 to the total count).

That's how implementation might look like:

public int twos(int n) {
    if (n % 2 != 0) return 0; // base case
    
    // recursive case
    return 1   twos(n / 2);
}

Or if you would use a so-called ternary operator (which is an equivalent of if-else) it can be written as:

public int twos(int n) {
    return n % 2 != 0 ? 0 : 1   twos(n / 2);
}

Usage example (in order to be able to call twos() from the main() add static modifier to it):

public static void main(String[] args) {
    System.out.println(twos(2));
    System.out.println(twos(4));
    System.out.println(twos(12));
    System.out.println(twos(38));
    System.out.println(twos(128));
}

Output:

1   // 2
2   // 4
2   // 12
1   // 38
7   // 128
  • Related