CoreNoob
CoreNoob

Reputation: 115

Primitive-recursive even/odd - what does it do exactly?

I know that this method checks if the integer is even, but how exactly? I understood on examples like fibonacci or factorial how recursion works but not on this on. I think I don't get it because of the syntax.

// Assume n >= 0 
public static boolean even(int n) { 
   return (n<=1) ? (n==0) : !even(n-1); 
} 

What my problem is: It's a boolean method, why is there no "true" or "false"? How exactly does it check if it's even? If I would do it in if-statements without recursion I would check it like this:

if((n%2) == 0)
return true;

Upvotes: 1

Views: 590

Answers (2)

Sean F
Sean F

Reputation: 4615

The statements

if((n%2) == 0)
    return true;
else
    return false;

is equivalent to

return (n%2) == 0;

any expression that evaluates to a boolean value can be used instead of directly using one of the two boolean values.

As for the function named "even", it basically says an integer is even if the previous integer is not even, unless it is smaller than one, in which case it is even if it is zero. Since it evaluates to a boolean value, so you can return it as the return value.

You should note that your function does not work for negative values.

Upvotes: 0

void
void

Reputation: 7890

it's a JAVA short if else:

condition ? trueCase: elseCase;

it equals to below syntax:

if(condition){
   trueCase;
}
else{
  elseCase;
}

In your code:

return (n<=1) ? (n==0) : !even(n-1); 

equals to:

if(n<=1)){
   if(n==0){
     return true;
   }
   else{
     return false;
   }
}
else{
  if(even(n-1)){
    return false;
  }
  else{
   return true;
  }
}

Upvotes: 1

Related Questions