Skip to content

Commit 8ca0efc

Browse files
committed
algorithm: add SquareRootLogarithmic algo and a test for it
1 parent 0fab492 commit 8ca0efc

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

Maths/SquareRootLogarithmic.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* @function squareRootLogarithmic
3+
* @description
4+
* Return the square root of 'num' rounded down
5+
* to the nearest integer.
6+
* More info: https://leetcode.com/problems/sqrtx/
7+
* @param {Number} num Number whose square of root is to be found
8+
* @returns {Number} Square root
9+
* @see [BinarySearch](https://en.wikipedia.org/wiki/Binary_search_algorithm)
10+
* @example
11+
* const num1 = 4
12+
* logarithmicSquareRoot(num1) // ====> 2
13+
* @example
14+
* const num2 = 8
15+
* logarithmicSquareRoot(num1) // ====> 2
16+
*
17+
*/
18+
const squareRootLogarithmic = (num) => {
19+
if (typeof num !== 'number') {
20+
throw new Error('Input data must be numbers')
21+
}
22+
let ans = 0
23+
let sqrt = 0
24+
let e = num
25+
26+
while (sqrt <= e) {
27+
const mid = Math.trunc((sqrt + e) / 2)
28+
if (mid * mid === num) {
29+
return mid
30+
} else if (mid * mid < num) {
31+
sqrt = mid + 1
32+
ans = mid
33+
} else {
34+
e = mid - 1
35+
}
36+
}
37+
38+
return ans
39+
}
40+
41+
export { squareRootLogarithmic }
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import { squareRootLogarithmic } from '../SquareRootLogarithmic'
2+
3+
describe('SquareRootLogarithmic', () => {
4+
test('Finding the square root of a positive integer', () => {
5+
expect(squareRootLogarithmic(4)).toEqual(2)
6+
expect(squareRootLogarithmic(16)).toEqual(4)
7+
expect(squareRootLogarithmic(8)).toEqual(2)
8+
})
9+
test('Throwing an exception', () => {
10+
expect(() => squareRootLogarithmic('not a number')).toThrow()
11+
expect(() => squareRootLogarithmic(true)).toThrow()
12+
})
13+
})

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy