Skip to content

Commit c39d666

Browse files
authored
algorithm: logarithmic square root (TheAlgorithms#1259)
* algorithm: add SquareRootLogarithmic algo and a test for it * fix: fix spelling errors * refactor: rename a variable "e" --> "edge"
1 parent 35e1fe6 commit c39d666

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 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 }
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