Skip to content

Instantly share code, notes, and snippets.

@zeraf29
Created April 23, 2017 09:07
Show Gist options
  • Save zeraf29/d5f06e2748d0a5fc3dda3d680539938b to your computer and use it in GitHub Desktop.
Save zeraf29/d5f06e2748d0a5fc3dda3d680539938b to your computer and use it in GitHub Desktop.
칸 아카데미. 재귀를 활용한 거듭제곱(정수일 경우)
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(n<0){
return 1/power(x,-n);
}
// recursive case: n is odd
if(isOdd(n)===true){
return x*power(x,n-1);
}
// recursive case: n is even
if(isEven(n)===true){
var y = power(x,n/2);
return y*y;
}
};
//power(3, -1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment