Adding math algorithm to compute power and its tests (#172)

* Adding math algorithm to compute power and its tests

* adding more test cases, updating compute power js

* Updating ReadMe for power computation algorithm
This commit is contained in:
HatimLokhandwala 2018-09-04 19:51:09 +05:30 committed by Oleksii Trekhleb
parent 518dc57388
commit 8676c1b9fe
3 changed files with 74 additions and 0 deletions

View File

@ -0,0 +1,35 @@
# Power(a,b)
This computes power of (a,b)
eg: power(2,3) = 8
power(10,0) = 1
The algorithm uses divide and conquer approach to compute power.
Currently the algorithm work for two positive integers X and Y
Lets say there are two numbers X and Y.
At each step of the algorithm:
1. if Y is even
then power(X, Y/2) * power(X, Y/2) is computed
2. if Y is odd
then X * power(X, Y/2) * power(X, Y/2) is computed
At each step since power(X,Y/2) is called twice, this is optimised by saving the result of power(X, Y/2) in a variable (lets say res).
And then res is multiplied by self.
Illustration through example
power (2,5)
- 2 * power(2,2) * power(2,2)
power(2,2)
- power(2,1) * power(2,1)
power(2,1)
- return 2
Going up the tree once the end values are computed
power(2,1) = 2
power(2,2) = power(2,1) * power(2,1) = 2 * 2 = 4
power(2,5) = 2 * power(2,2) * power(2,2) = 2 * 4 * 4 = 32
Complexity relation: T(n) = T(n/2) + 1
Time complexity of the algorithm: O(logn)

View File

@ -0,0 +1,16 @@
import computePower from '../power';
describe('computePower', () => {
it('should compute Power', () => {
expect(computePower(1, 1)).toBe(1);
expect(computePower(2, 0)).toBe(1);
expect(computePower(3, 4)).toBe(81);
expect(computePower(190, 2)).toBe(36100);
expect(computePower(16, 16)).toBe(18446744073709552000);
expect(computePower(100, 9)).toBe(1000000000000000000);
expect(computePower(9, 16)).toBe(1853020188851841);
expect(computePower(11, 5)).toBe(161051);
expect(computePower(13, 11)).toBe(1792160394037);
expect(computePower(7, 21)).toBe(558545864083284000);
});
});

View File

@ -0,0 +1,23 @@
/**
* @param {number1} number
* @param {number2} number
* @return {number1^number2}
*/
// recursive implementation to compute power
export default function computePower(number1, number2) {
let val = 0;
let res = 0;
if (number2 === 0) { // if number2 is 0
val = 1;
} else if (number2 === 1) { // if number2 is 1 return number 1 as it is
val = number1;
} else if (number2 % 2 === 0) { // if number2 is even
res = computePower(number1, number2 / 2);
val = res * res;
} else { // if number2 is odd
res = computePower(number1, Math.floor(number2 / 2));
val = res * res * number1;
}
return val;
}