Skip to content

Commit 6bc23f0

Browse files
committed
Special Problem
1 parent 8d51fce commit 6bc23f0

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Math/primeNumberDifference.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
'''
2+
Given two integers find the maximum difference between two prime numbers contained in their range. For e.g. if you are given two integers 2 and 6, i.e range [2,6] inclusive, the two farthest prime numbers are 2 & 5 and the answer is 3. If there are no prime numbers in the range, print 0.
3+
'''
4+
from bisect import bisect_left, bisect_right
5+
N = 10**6
6+
def getPrimes(N):
7+
primes = [2]
8+
check = [1] * N
9+
for i in range(3,N,2):
10+
if check[i]:
11+
primes.append(i)
12+
for j in range(3*i,N,2*i):
13+
check[j] = 0
14+
return primes
15+
16+
primes = getPrimes(N)
17+
t = int(raw_input())
18+
for i in range(t):
19+
n1, n2 = map(int,raw_input().split())
20+
i1 = bisect_right(primes,n1)
21+
i2 = bisect_left(primes,n2)
22+
if i1 > 0 and primes[i1-1] == n1:
23+
i1 -= 1
24+
while i2 > 0 and primes[i2] > n2:
25+
i2 -= 1
26+
27+
if i2 + 1 < len(primes) and primes[i2+1] <= n2:
28+
i2 += 1
29+
p1 = primes[i1]
30+
p2 = primes[i2]
31+
#print p1, p2
32+
if p1 < p2:
33+
print p2-p1
34+
else:
35+
print 0

0 commit comments

Comments
 (0)