Created
October 7, 2019 14:38
-
-
Save mvoitko/7f797e2c607b29e9946f0f010ec9d163 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# f(x) = x*x*x + a*x + b; a, b > 0, x - integer | |
# find x0, such that f(x0) = c, c > 0 | |
| |
# Для начала найдем левую границу, выберем произвольную отрицательную точку (например -1). | |
# Будем удваивать ее до тех пор, пока значение в ней будет больше заданного значения. | |
# | |
# Для того, чтобы найти правую границу, выберем произвольную положительную точку (например 1). | |
# Будем удваивать ее до тех пор, пока значение функции в этой точке меньше заданного. | |
| |
def findLeftBoard(C): | |
x = -1 | |
while f(x) > C | |
x = x * 2 | |
return x | |
| |
def findRightBoard(C): | |
x = 1 | |
while f(x) < C | |
x = x * 2 | |
return x | |
| |
def binSearch(C): | |
left = findLeftBoard(C) | |
right = findRightBoard(C) | |
while right - left > 1: | |
mid = (left + right) / 2 | |
if f(mid) >= C | |
right = mid | |
else | |
left = mid | |
if f(right) == C: | |
return right |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment