Advertisement
YaBoiSwayZ

Parallel Prime Palindrome Finder

May 26th, 2024
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.68 KB | Source Code | 0 0
  1. from multiprocessing import Pool, cpu_count
  2. import math
  3. import time
  4.  
  5. def sieve_of_eratosthenes(limit):
  6.     prime_flags = [True] * (limit + 1)
  7.     prime_flags[0] = prime_flags[1] = False
  8.     for base in range(2, int(math.sqrt(limit)) + 1):
  9.         if prime_flags[base]:
  10.             for multiple in range(base * base, limit + 1, base):
  11.                 prime_flags[multiple] = False
  12.     return prime_flags
  13.  
  14. def generate_palindrome_prime(start, end, prime_flags):
  15.     special_primes = []
  16.     for i in range(start, end):
  17.         str_i = str(i)
  18.         palindrome = int(str_i + str_i[-2::-1])
  19.         if palindrome > end:
  20.             break
  21.         if prime_flags[palindrome]:
  22.             special_primes.append(palindrome)
  23.     return special_primes
  24.  
  25. def parallel_processing(range_start, range_end):
  26.     num_processes = cpu_count()
  27.     pool = Pool(processes=num_processes)
  28.     chunk_size = (range_end - range_start) // num_processes
  29.     prime_flags = sieve_of_eratosthenes(range_end)
  30.     tasks = [(range_start + i * chunk_size, min(range_start + (i + 1) * chunk_size, range_end), prime_flags) for i in range(num_processes)]
  31.     results = pool.starmap(generate_palindrome_prime, tasks)
  32.     pool.close()
  33.     pool.join()
  34.     return [prime for sublist in results for prime in sublist]
  35.  
  36. if __name__ == '__main__':
  37.     range_start = 110000
  38.     range_end = 150000
  39.  
  40.     start_time = time.time()
  41.     special_primes = parallel_processing(range_start, range_end)
  42.     end_time = time.time()
  43.  
  44.     print("Special numbers:", special_primes[:3], "...", special_primes[-3:])
  45.     print("Total amount of special numbers:", len(special_primes))
  46.     print("Time passed:", end_time - start_time, "seconds")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement