mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 00:01:37 +08:00
algorithm: logarithmic square root (#1259)
* algorithm: add SquareRootLogarithmic algo and a test for it * fix: fix spelling errors * refactor: rename a variable "e" --> "edge"
This commit is contained in:
41
Maths/SquareRootLogarithmic.js
Normal file
41
Maths/SquareRootLogarithmic.js
Normal file
@ -0,0 +1,41 @@
|
||||
/**
|
||||
* @function squareRootLogarithmic
|
||||
* @description
|
||||
* Return the square root of 'num' rounded down
|
||||
* to the nearest integer.
|
||||
* More info: https://leetcode.com/problems/sqrtx/
|
||||
* @param {Number} num Number whose square of root is to be found
|
||||
* @returns {Number} Square root
|
||||
* @see [BinarySearch](https://en.wikipedia.org/wiki/Binary_search_algorithm)
|
||||
* @example
|
||||
* const num1 = 4
|
||||
* logarithmicSquareRoot(num1) // ====> 2
|
||||
* @example
|
||||
* const num2 = 8
|
||||
* logarithmicSquareRoot(num1) // ====> 2
|
||||
*
|
||||
*/
|
||||
const squareRootLogarithmic = (num) => {
|
||||
if (typeof num !== 'number') {
|
||||
throw new Error('Input data must be numbers')
|
||||
}
|
||||
let answer = 0
|
||||
let sqrt = 0
|
||||
let edge = num
|
||||
|
||||
while (sqrt <= edge) {
|
||||
const mid = Math.trunc((sqrt + edge) / 2)
|
||||
if (mid * mid === num) {
|
||||
return mid
|
||||
} else if (mid * mid < num) {
|
||||
sqrt = mid + 1
|
||||
answer = mid
|
||||
} else {
|
||||
edge = mid - 1
|
||||
}
|
||||
}
|
||||
|
||||
return answer
|
||||
}
|
||||
|
||||
export { squareRootLogarithmic }
|
13
Maths/test/SquareRootLogarithmic.test.js
Normal file
13
Maths/test/SquareRootLogarithmic.test.js
Normal file
@ -0,0 +1,13 @@
|
||||
import { squareRootLogarithmic } from '../SquareRootLogarithmic'
|
||||
|
||||
describe('SquareRootLogarithmic', () => {
|
||||
test('Finding the square root of a positive integer', () => {
|
||||
expect(squareRootLogarithmic(4)).toEqual(2)
|
||||
expect(squareRootLogarithmic(16)).toEqual(4)
|
||||
expect(squareRootLogarithmic(8)).toEqual(2)
|
||||
})
|
||||
test('Throwing an exception', () => {
|
||||
expect(() => squareRootLogarithmic('not a number')).toThrow()
|
||||
expect(() => squareRootLogarithmic(true)).toThrow()
|
||||
})
|
||||
})
|
Reference in New Issue
Block a user