"""
The prime numbers are not regularly spaced. For example from 2 to 3 the gap is 1. From 3 to 5 the gap is 2. From 7 to 11 it is 4. 
Between 2 and 50 we have the following pairs of 2-gaps primes: 3-5, 5-7, 11-13, 17-19, 29-31, 41-43
A prime gap of length n is a run of n-1 consecutive composite numbers between two successive primes 
(see: http://mathworld.wolfram.com/PrimeGaps.html).

We will write a function gap with parameters:
g (integer >= 2) which indicates the gap we are looking for
m (integer > 2) which gives the start of the search (m inclusive)
n (integer >= m) which gives the end of the search (n inclusive)
In the example above gap(2, 3, 50) will return [3, 5] or (3, 5) or {3, 5} which is the first pair between 3 and 50 with a 2-gap.
So this function should return the first pair of two prime numbers spaced with a gap of g between the limits m, n 
if these numbers exist otherwise nil or null or None or Nothing (depending on the language).

gap(6,100,110) --> nil or {0, 0} : between 100 and 110 we have 101, 103, 107, 109 but 101-107is not a 6-gap because 
there is 103in between and 103-109is not a 6-gap because there is 107in between.
"""


def gap(g, m, n):
    num1 = 0  # here we are shifting num2 to num1 at each iteration
    num2 = 0
    for i in range(m, n + 1):
        if isprime(i):
            if num1 == 0:
                num1 = i
            elif num2 == 0:
                num2 = i
            else:
                num1 = num2
                num2 = i
            # print(num1, num2)
        if num2 - num1 == g:
            return [num1, num2]


def isprime(n):
    for i in range(2, int(n ** 0.5 + 1)):
        if n % i == 0:
            return False
    return True


# def isprime(n):
#     if n <= 0 or n == 1:
#         return False
#     i = 2
#     while i <= n ** 0.5:
#         if n % i == 0:
#             return False
#         i += 1
#     return True


# print(gap(2, 100, 110))  # [101, 103]
# print(gap(4, 100, 110))  # [103, 107]
# print(gap(6, 100, 110))  # None
# print(gap(10, 300, 400))  # [337, 347]
print(gap(8, 300, 400))  #


# codewars solution 1
def gap(g, m, n):
    previous_prime = n
    for i in range(m, n + 1):
        if is_prime(i):
            if i - previous_prime == g:
                return [previous_prime, i]
            previous_prime = i
    return None


def is_prime(n):
    for i in range(2, int(n ** 0.5 + 1)):
        if n % i == 0:
            return False
    return True


# codewars solution 2
def gap(g, m, n):
    prime = 0
    for i in range(m, n + 1):
        for j in range(2, int(i ** 0.5) + 1):
            if i % j == 0:
                break
        else:
            if i - prime == g:
                return [prime, i]
            else:
                prime = i

