Sqrt(n)
In this section, we will practice with the BS algorithm.
The first task will be to find the square root of the number.
Look at the explanation of the task! How does it work?
Use hints if needed! Be careful with the tabulation!
Let's practice!
Завдання
Swipe to start coding
- Set condition if the
x
equals0
or1
. - Set the while loop to work while the
left
is lower or equals theright
. - Set condition if the square of the middle elements equals
x
. - Set condition if the square of the middle elements is lower than
x
. - Update the
left
. Theleft
equals themiddle + 1
. - Update the
result
. Theresult
equals themiddle
. - Update the
right
. Theright
equals themiddle - 1
. - Test the function.
Рішення
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def sqrt_binarySearch(x):
# Set condition if the 'x' equals 0 or 1
if (x == 0 or x == 1):
return x
left, right = 1, x
# Set the while loop to work while the 'left' is lower or equals the 'right'
while (left <= right):
middle = (left + right) // 2
# Set condition if the square of the middle elements equals 'x'
if (middle * middle == x):
return middle
# Set condition if the square of the middle elements is lower than 'x'
elif (middle * middle < x):
# Update the 'left'
left = middle + 1
# Update the 'result'
result = middle
else:
# Update the 'right'
right = middle - 1
return result
# Testing
x = 11
# Test the function with the 'x' variable
test = sqrt_binarySearch(x)
print(test)
Все було зрозуміло?
Дякуємо за ваш відгук!
Секція 2. Розділ 1
single
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def sqrt_binarySearch(x):
# Set condition if the 'x' equals 0 or 1
if (x == _ _ _ or _ _ _ == _ _ _):
return x
left, right = 1, x
# Set the while loop to work while the 'left' is lower or equals the 'right'
_ _ _ (_ _ _ <= _ _ _):
middle = (left + right) // 2
# Set condition if the square of the middle elements equals 'x'
if (_ _ _ == x):
return middle
# Set condition if the square of the middle elements is lower than 'x'
elif (_ _ _ < x):
# Update the 'left'
_ _ _ = middle + _ _ _
# Update the 'result'
result = _ _ _
else:
# Update the 'right'
right = _ _ _
return result
# Testing
x = 11
# Test the function with the 'x' variable
test = _ _ _(_ _ _)
print(test)
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат