File tree Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Original file line number Diff line number Diff line change 1+ import { isEven } from './IsEven'
2+
3+ /**
4+ * This algorithm is divide the n by 2 every time and pass this to recursive call to find the result of smaller result.
5+ * why? Because
6+ * x^n => [if n is even] x^(n / 2) * x^(n / 2) (example : 7^4 => 7^2 * 7^2)
7+ * [if n is odd] x^(n / 2) * x^(n / 2) * x (example : 7^5 => 7^2 * 7^2 * 7)
8+ * and repeat the above step until we reach to the base case.
9+ *
10+ * @function PowLogarithmic
11+ * @description Given two integers x and n, return x^n in logarithmic complexity.
12+ * @param {Integer } x - The input integer
13+ * @param {Integer } n - The input integer
14+ * @return {Integer } - Returns x^n.
15+ * @see [Pow-Logarithmic](https://www.geeksforgeeks.org/write-a-c-program-to-calculate-powxn/)
16+ */
17+ const powLogarithmic = ( x , n ) => {
18+ if ( n === 0 ) return 1
19+ const result = powLogarithmic ( x , Math . floor ( n / 2 ) )
20+ if ( isEven ( n ) ) {
21+ return result * result
22+ }
23+ return result * result * x
24+ }
25+
26+ export { powLogarithmic }
Original file line number Diff line number Diff line change 1+ import { powLogarithmic } from '../PowLogarithmic'
2+
3+ describe ( 'PowLogarithmic' , ( ) => {
4+ it ( 'should return 1 for numbers with exponent 0' , ( ) => {
5+ expect ( powLogarithmic ( 2 , 0 ) ) . toBe ( 1 )
6+ } )
7+
8+ it ( 'should return 0 for numbers with base 0' , ( ) => {
9+ expect ( powLogarithmic ( 0 , 23 ) ) . toBe ( 0 )
10+ } )
11+
12+ it ( 'should return the base to the exponent power' , ( ) => {
13+ expect ( powLogarithmic ( 24 , 4 ) ) . toBe ( 331776 )
14+ } )
15+ } )
You can’t perform that action at this time.
0 commit comments