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 toaifbis 0, andbifais 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)ifais greater than or equal tob, or(a, b % a)ifbis greater thana. This step is based on the Euclidean algorithm, which states that the GCD of two numbersaandbis the same as the GCD ofband the remainder ofadivided byb(i.e.a % b). - This recursive step continues until the base case is reached, at which point the function returns the GCD of
aandb.
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
lowandhighpointers to the start and end of the array, respectively. - It uses a
whileloop to iterate until thelowandhighpointers meet each other. - In each iteration, it finds the middle element of the current subarray (defined by the
lowandhighpointers) and compares it to the targetx. - If the middle element is equal to
x, it returns the index of the middle element. - If
xis greater than the middle element, it updates thelowpointer to be the element immediately after the middle element, so that the search will continue on the right (greater) half of the array. - If
xis smaller than the middle element, it updates thehighpointer 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
whileloop completes without findingx, it returns -1 to indicate thatxis not present in the array.