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
def largestGap(num):
f_prime=0;"""to store the latest prime number"""
s_prime=0;"""To store the previous prime number"""
gap=0;"""to store the gap between two successive prime numbers"""
for j in range(2,num):
cnt=0;
for i in range(2,j/2):
if(j%i == 0):
cnt=1;
break;
if(cnt == 0):
s_prime=f_prime;
f_prime=j;
if(gap<f_prime-s_prime):
gap=f_prime-s_prime;
print(gap);
largestGap(100);
The j loop is to iterate from 2 till the number passed to the function.
i loop is to check if the number passed from j loop is prime or not.
it checks if the value of j is divisible by 2 till number/2.if divisible,breaks from the loop;
if not divisble by any number from 2 till number/2,its a prime.this value is assigned to f_prime and the previous number is assigned to s_prime.
then checks if gap is less than f_prime-s_prime. if yes gap is assigned this value.