1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
|
import timeit from math import sqrt from collections import deque from collections import defaultdict
def sieve_of_primes_up_to(n): sieve = [True] * (n + 1) for p in range(2, round(sqrt(n)) + 1): if sieve[p]: for i in range(p * p, n + 1, p): sieve[i] = False return sieve
def primes_in_window(size, lower_bound, upper_bound): if size > upper_bound - lower_bound + 1: print('Window size is too large for these bounds,', 'leaving it there.' ) return
dict_length = defaultdict(list) dq_window = deque() prime_list = sieve_of_primes_up_to(upper_bound) cur_number = 1 while cur_number < len(prime_list): if cur_number >= lower_bound: if dq_window and cur_number - dq_window[0] >= size: dq_window.popleft() if prime_list[cur_number]: dq_window.append(cur_number) length_of_window = len(dq_window) dict_length[length_of_window].append([dq_window[0], dq_window[-1]])
cur_number += 1 if dict_length: max_length = max(dict_length.keys()) else: print(f'There is no prime in a window of size {size}.') return if max_length == 1: print(f'There is at most one prime in a window of size {size}.') elif max_length > 1: print(f'There are at most {max_length} primes in a window of size {size}.') for value in dict_length[max_length]: print(f'In some window, the smallest prime is {value[0]} and the largest one is {value[1]}.')
|