3.9 & 3.11 Notes and Hacks
Hacks
import random
def gcd(a, b):
# base case
if a == 0:
return b
if b == 0:
return a
# recursive step
if a >= b:
return gcd(a % b, b)
else:
return gcd(a, b % a)
num1 = random.randint(0,1000)
num2 = random.randint(0,1000)
print("Numbers being compared:", num1, "&", num2)
print("The greatest common divisor between", num1, "&", num2, "is:")
gcd(num1, num2)
- The function starts by defining a base case where
gcd(a, b)
is equal toa
ifb
is 0, andb
ifa
is 0. This is because the GCD of a number and 0 is always the number itself. - The next step is the recursive step, where the function calls itself with the arguments
(a % b, b)
ifa
is greater than or equal tob
, or(a, b % a)
ifb
is greater thana
. This step is based on the Euclidean algorithm, which states that the GCD of two numbersa
andb
is the same as the GCD ofb
and the remainder ofa
divided byb
(i.e.a % b
). - This recursive step continues until the base case is reached, at which point the function returns the GCD of
a
andb
.
Binary Search Hacks
def binary_search(array, x):
low = 0
high = len(array) - 1
while low <= high:
mid = low + (high - low) // 2
if array[mid] == x:
return mid
elif array[mid] < x:
low = mid + 1
else:
high = mid - 1
return -1
array = [3, 4, 5, 6, 7, 8, 9]
x = 4
result = binary_search(array, x)
if result != -1:
print("Element is present at index " + str(result))
else:
print("Element is not present in the array")
This implementation follows the steps outlined in the previous section:
- It initializes the
low
andhigh
pointers to the start and end of the array, respectively. - It uses a
while
loop to iterate until thelow
andhigh
pointers meet each other. - In each iteration, it finds the middle element of the current subarray (defined by the
low
andhigh
pointers) and compares it to the targetx
. - If the middle element is equal to
x
, it returns the index of the middle element. - If
x
is greater than the middle element, it updates thelow
pointer to be the element immediately after the middle element, so that the search will continue on the right (greater) half of the array. - If
x
is smaller than the middle element, it updates thehigh
pointer to be the element immediately before the middle element, so that the search will continue on the left (lower) half of the array. - If the
while
loop completes without findingx
, it returns -1 to indicate thatx
is not present in the array.