Write a smallest_gap(start_num, end_num) function that finds smallest gap between successive primes, considering prime numbers in the range from start_num to end_num (inclusive).
For example, start_num = 5 and end_num = 12, the prime numbers in that range are: [5, 7, 11]. The smallest gap between any two prime numbers in this list is 2, so the function would return 2.
Some example test cases (include these test cases in your program):
>>> print(smallest_gap(5, 12))
2
# The primes between 1000 and 1020 are 1009, 1013, 1019 so the smallest gap
# is 4 as 1013 – 1009 = 4
>>> print(smallest_gap(1000,1020))
4
In PyCharm
def smallest_gap(start_num, end_num): lst = [] for n in range(start_num, end_num + 1): is_prime = n > 1 for i in range(2, n): if n % i == 0: is_prime = False if is_prime: lst.append(n) min_gap = None for i in range(1, len(lst)): if min_gap is None or lst[i] - lst[i - 1] < min_gap: min_gap = lst[i] - lst[i - 1] return min_gap # Testing the function here. ignore/remove the code below if not required print(smallest_gap(5, 12)) print(smallest_gap(1000, 1020))
Get Answers For Free
Most questions answered within 1 hours.