how to see if a number and pair in java with recursion

0
var isEven = function(n) {
    return n % 2 === 0;
};

var isOdd = function(n) {
    return !isEven(n);
};

var power = function(x, n) {
    println("Computing " + x + " raised to power " + n + ".");
    // base case
    if (n===0){
        return 1;
    }
    // recursive case: n is negative 
    if(isOdd(n)!==0){
        return x * power(x,n-1) ;
    }
    // recursive case: n is odd
    if (isEven(n%2)===0){//aqui nao estou conseguindo

        var m =-1;
        return isEven(m*n-1);
    
asked by anonymous 31.10.2015 / 02:56

1 answer

0

So I understand your algorithm is trying to make an exponential x ^ n (at least that's what the names of the variables and comments suggest).

Maybe you are not understanding what you should do or are having problems understanding the algorithm. Your comments do not agree with the code.

Anyway,

You should note that if the n exponent is even.

  

x ^ n = x ^ (n / 2) * x ^ (n / 2) // attention! use integer division

I also find it interesting that you change this part of the code. No split remainder is required 2 times.

 if (isEven(n%2)===0){//aqui nao estou conseguindo. Por que se o numero é par ele não entra aqui =)

Do this:

 if (isEven(n)!==0){
    
31.10.2015 / 14:33