Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitc39d666

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

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+
constsquareRootLogarithmic=(num)=>{
19+
if(typeofnum!=='number'){
20+
thrownewError('Input data must be numbers')
21+
}
22+
letanswer=0
23+
letsqrt=0
24+
letedge=num
25+
26+
while(sqrt<=edge){
27+
constmid=Math.trunc((sqrt+edge)/2)
28+
if(mid*mid===num){
29+
returnmid
30+
}elseif(mid*mid<num){
31+
sqrt=mid+1
32+
answer=mid
33+
}else{
34+
edge=mid-1
35+
}
36+
}
37+
38+
returnanswer
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)

[8]ページ先頭

©2009-2025 Movatter.jp