Friday, June 2, 2017

Next & Previous Immediate Prime Difference

A number N is passed as the input. The program must print the difference between the next immediate prime number and the previous immediate prime number. If the given number N itself is a prime number then print 0 (zero). 

Input Format: 

The first line will contain the value of the number N. 

Output Format: 

The difference between the next immediate prime number and the previous immediate prime number for N. 

Example Input/Output 1: 

Input: 14 
Output: 4 
Explanation: The next immediate prime number is 17. The previous immediate prime number is 13. Hence their difference = 17-13 = 4 is printed as output. 

Solution:

def prim3(n,a):
    x = n
    for i in range(2,int((n/2) + 5)):
        if n%i == 0 and a:
            n -= 1
        elif n%i == 0:
            n += 1
    return 0 if n == x else n
n = int(input())
print(prim3(n,0)-prim3(n,1))

Share: