File tree Expand file tree Collapse file tree 2 files changed +54
-0
lines changed Expand file tree Collapse file tree 2 files changed +54
-0
lines changed Original file line number Diff line number Diff line change 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 answer = 0
23+ let sqrt = 0
24+ let edge = num
25+
26+ while ( sqrt <= edge ) {
27+ const mid = Math . trunc ( ( sqrt + edge ) / 2 )
28+ if ( mid * mid === num ) {
29+ return mid
30+ } else if ( mid * mid < num ) {
31+ sqrt = mid + 1
32+ answer = mid
33+ } else {
34+ edge = mid - 1
35+ }
36+ }
37+
38+ return answer
39+ }
40+
41+ export { squareRootLogarithmic }
Original file line number Diff line number Diff line change 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+ } )
You can’t perform that action at this time.
0 commit comments