from mpi4py import MPI import numpy def computeParallelFactorial(start, terms): nums = numpy.arange(start, start + terms, 1) # Local reduce partial = numpy.multiply.reduce(nums) # Global reducce fact = comm.allreduce(partial, op=MPI.PROD) return fact if __name__ == "__main__": from sys import argv # Establish Communicator comm = MPI.COMM_WORLD # Obtain rank rank = comm.Get_rank() # Get number of processes np = comm.Get_size() terms = int(argv[1]) if terms % np != 0: print("terms % np != 0") exit() l_terms = terms // np start = l_terms*rank+1 result = computeParallelFactorial(start, l_terms) if rank == 0: print("{:d}! computed with {} processes is {}".format(terms, np, result))