Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
998 B
3
Indexable
Never
from mpi4py import MPI
import math

def is_prime(n):
    if n <= 1:
        return False
    if n <= 3:
        return True
    if n % 2 == 0 or n % 3 == 0:
        return False
    i = 5
    while i * i <= n:
        if n % i == 0 or n % (i + 2) == 0:
            return False
        i += 6
    return True

def find_max_prime(start, end):
    max_prime = 0
    for num in range(start, end + 1):
        if is_prime(num):
            max_prime = max(max_prime, num)
    return max_prime

comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()

N = 1000000  # Define the upper limit of the interval
interval_size = N // size
start = rank * interval_size + 1
end = (rank + 1) * interval_size if rank != size - 1 else N

local_max_prime = find_max_prime(start, end)

global_max_prime = comm.reduce(local_max_prime, op=MPI.MAX, root=0)

if rank == 0:
    print("The maximum prime number in the interval [1, {}] is: {}".format(N, global_max_prime))
Leave a Comment