In: Computer Science
Given a number n, what is the largest gap between successive primes which are less than number n?
For example, if n = 12, the prime numbers less than 12 are: [2, 3, 5, 7, 11]. The largest gap between any two prime numbers in this list is 4, so the function would return '4'.
>>>print(largestGap(12)) 4
Write Python code to solve this problem, and include the following 3 test cases in your answer.
>>>print(largestGap(100)) 8 >>>print(largestGap(1000)) 20 >>>print(largestGap(10000)) 36
In PyCharm
def checkIfNumberIsPrime(num):
if num >1:
for i in range(2,num):
if num%i ==0:
return 0
return 1
else:
return 0
#target find the max difference between 2 consecutive primes
previousPrime=1 #assuming first prime is stored in previousPrime and as first prime is 1 so we initialize the value to 1
maxDifference=0 # initialize the maxDifference with default value 0
number=int(input("Enter a number")) #ask the user a number upto which we want to find the max difference
for i in range(2,number): #as first number is initialized to 1 so we start iteration from 2 and repeat it till the user entered number
x=checkIfNumberIsPrime(i) # checks if the number in current iteration is prime or not
if(x==1): #this block gets executed if the number is prime
if i-previousPrime > maxDifference: #now check if the difference between previousPrime and current prime i.e number in current iteration is greater than maxDifferent if yes then we update the maxDifferent to the difference between previousPrime and current prime number and as we will have to find difference between cosecutive prime numbers so we update the previousPrime with currentPrime
maxDifference=i-previousPrime
previousPrime=i
print("Max difference between primes:",maxDifference)