Know if a number is even or odd using indirect recursion

2

Is it possible to solve an exercise where you are asked to know if a number is even or odd using indirect recursion?

The slogan is: Make a recursive Algorithm that allows to know if a number is odd using indirect recursion

What I do is the following but I do not know if the concept is right:

public class EjercicioTrece {

public static void main(String[]args){

    testPositivo(5);
    testPositivo(-1);
    testPositivo(100);
    testPositivo(-1000);

}


public static void testPositivo(int num1){
    System.out.println(esPositivo(num1));
}


public static boolean esPositivo(int num){

    if(num < 0){
        return false;
    }else {
        return true;
    }


}
    
asked by Maxi Hernandez 20.09.2017 в 11:47
source

2 answers

4

It's a classic example to see how indirect recursion works. The difficulty lies mainly in discovering how to apply recursion rather than in its programming.

public static boolean impar (int num){
    if (num == 0) 
        return false;
    else
        return par(num-1);
}

public static boolean par (int num) {
    if (num == 0) 
        return true;
    else
        return impar(num-1);
}

In this way, if for example we call the method impar(3) the program would par(2) -> impar(1) -> par(0) -> true affirming how we know that three is odd . If we do instead par(3) will do impar(2) -> par(1) -> impar(0) -> false , it is messy but not difficult.

The best way to learn is to look at a few examples, understand how it works (personally making a trace by hand is how it works best for me) and then try to do some exercise.

I hope it has helped you;)

    
answered by 20.09.2017 в 14:34
1

To know if a number is even or odd you do not need recursion, this sentence would say if a number is even or odd:

int num=0;

if(num%2==0){
System.out.println("El numero es par");
}else
System.out.println("El numero es impar");

That is, if a number is divisible by 2 it will be even, if it is not divisible by 2 it is odd. recursion is used as an iterative sentence, it would resemble a loop, and you do not need something like that to determine if a number is even or odd

    
answered by 20.09.2017 в 11:52