File tree Expand file tree Collapse file tree 4 files changed +74
-0
lines changed
interview_training/cracking_the_coding_interview/big_o Expand file tree Collapse file tree 4 files changed +74
-0
lines changed Original file line number Diff line number Diff line change 1+ def sqrt (n ):
2+ return sqrt_helper (n , 1 , n )
3+
4+ def sqrt_helper (n , min , max ):
5+ if min > max :
6+ return - 1
7+
8+ guess = (min + max ) / 2
9+
10+ if guess * guess > n :
11+ return sqrt_helper (n , min , guess - 1 )
12+ elif guess * guess < n :
13+ return sqrt_helper (n , guess + 1 , max )
14+ else :
15+ return guess
16+
17+ print (sqrt (100 ))
18+ print (sqrt (9 ))
19+ print (sqrt (25 ))
20+ print (sqrt (3 ))
21+
22+ # Complexity: O(log N) --> It is a binary search algorithm
Original file line number Diff line number Diff line change 1+ from math import sqrt
2+
3+ def square_root (n ):
4+ for guess in range (int (sqrt (n ))+ 1 ):
5+ if guess * guess == n :
6+ return guess
7+
8+ return - 1
9+
10+ print (square_root (100 ))
11+ print (square_root (9 ))
12+ print (square_root (25 ))
13+ print (square_root (3 ))
14+
15+ # Complexity: O(log N) --> It is a binary search algorithm
Original file line number Diff line number Diff line change 1+ def sqrt (n ):
2+ return sqrt_helper (n , 1 , n )
3+
4+ def sqrt_helper (n , min , max ):
5+ if min > max :
6+ return - 1
7+
8+ guess = (min + max ) / 2
9+
10+ if guess * guess > n :
11+ return sqrt_helper (n , min , guess - 1 )
12+ elif guess * guess < n :
13+ return sqrt_helper (n , guess + 1 , max )
14+ else :
15+ return guess
16+
17+ print (sqrt (100 ))
18+ print (sqrt (9 ))
19+ print (sqrt (25 ))
20+ print (sqrt (3 ))
21+
22+ # Complexity: O(log N) --> It is a binary search algorithm
Original file line number Diff line number Diff line change 1+ from math import sqrt
2+
3+ def square_root (n ):
4+ for guess in range (int (sqrt (n ))+ 1 ):
5+ if guess * guess == n :
6+ return guess
7+
8+ return - 1
9+
10+ print (square_root (100 ))
11+ print (square_root (9 ))
12+ print (square_root (25 ))
13+ print (square_root (3 ))
14+
15+ # Complexity: O(log N) --> It is a binary search algorithm
You can’t perform that action at this time.
0 commit comments