In: Computer Science
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.
You may want to modify your solution from Problem 1 on Assignment 4, or you can use this starter code that has the sieve() algorithm we studied to calculate all the prime numbers up to n.
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 python
Python code and screenshort of output shown below
import array
def SieveOfPrime(start_num,end_num):
# array of type boolean with True values in it
s=[]# empty array names s
prime = [True for i in range(end_num+1)]
p = 2
while (p * p <= end_num):
# If it remain unchanged it is prime
if (prime[p] == True):
# updating all the multiples
for i in range(p * p, end_num+1, p):
prime[i] = False
p += 1
c=0
print ('Prime numbers(',start_num,',',end_num,')are:')
for p in range(start_num,end_num+1):
if prime[p]:
s.insert(c,p)#store only prime numbers in array s
c=c+1
print (p,end=" ")
if c>=2:#count of prime numbers greater than
val=s[1]-s[0]#assign difference of first two numbers as a smallest
gap for comaprison
else:#one prime number
return s[0]
for i in range(0,c-1):
diff=s[i+1]-s[i]
if val>diff:#comparing for finding smallest gap between
consecutive prime numbers
val=diff
return val#return smallest gap
# main
if __name__=='__main__':
n = 33
print('\nThe smallest gap
is:',SieveOfPrime(1000,1020))
screenshort of output