Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from multiprocessing import Pool, cpu_count
- import math
- import time
- def sieve_of_eratosthenes(limit):
- prime_flags = [True] * (limit + 1)
- prime_flags[0] = prime_flags[1] = False
- for base in range(2, int(math.sqrt(limit)) + 1):
- if prime_flags[base]:
- for multiple in range(base * base, limit + 1, base):
- prime_flags[multiple] = False
- return prime_flags
- def generate_palindrome_prime(start, end, prime_flags):
- special_primes = []
- for i in range(start, end):
- str_i = str(i)
- palindrome = int(str_i + str_i[-2::-1])
- if palindrome > end:
- break
- if prime_flags[palindrome]:
- special_primes.append(palindrome)
- return special_primes
- def parallel_processing(range_start, range_end):
- num_processes = cpu_count()
- pool = Pool(processes=num_processes)
- chunk_size = (range_end - range_start) // num_processes
- prime_flags = sieve_of_eratosthenes(range_end)
- tasks = [(range_start + i * chunk_size, min(range_start + (i + 1) * chunk_size, range_end), prime_flags) for i in range(num_processes)]
- results = pool.starmap(generate_palindrome_prime, tasks)
- pool.close()
- pool.join()
- return [prime for sublist in results for prime in sublist]
- if __name__ == '__main__':
- range_start = 110000
- range_end = 150000
- start_time = time.time()
- special_primes = parallel_processing(range_start, range_end)
- end_time = time.time()
- print("Special numbers:", special_primes[:3], "...", special_primes[-3:])
- print("Total amount of special numbers:", len(special_primes))
- print("Time passed:", end_time - start_time, "seconds")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement