You are on page 1of 3

COMSATS UNIVERSITY ISLAMABAD

ABBOTTABAD CAMPUS
PARALLEL AND DISTRIBUTED COMPUTING
ASSIGNMENT 3
SUBMITTED BY: MUHAMMAD SOHAIB JAVAID
REG NO.: FA18-BCS-036
SUBMITTED TO: MUHAMMAD MATEEN YAQOOB
DATE OF SUBMISSION: 2 JUNE,2022.
Part 1. Develop parallel version of factorial calculation program for distributed
memory using MPI. The sequential version is given below to start with.

Ans
#include<stdio.h>
long fact(int n)
{
if(n<=1)
return 1;
else
return n*fact(n-1);
}
int main()
{
int i,rank,size;
long ans;
MPI_Init(NULL,NULL);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&size);
if(rank==0)
{
printf("Enter number: ");
scanf("%d",&i);
}
MPI_Bcast(&n,1,MPI_INT,0,MPI_COMM_WORLD);
ans=fact(i);
if(rank==0)
{
printf("Computed answer: %ld\n",ans);
}
MPI_Barrier(MPI_COMM_WORLD);
MPI_Reduce(&ans,&ans,1,MPI_LONG,MPI_SUM,0,MPI_COMM_WORLD);
if(rank==0)
{
printf("Answer: %ld\n",ans);
}
MPI_Finalize();
return 0;
}

Explanation:
This code computes the factorial utilizing the MPI library. Number is input by client on processor 0, and the
factorial is determined on that processor. The outcome is then communicated to processor 1, which prints
it out. At long last, the two processors synchronize utilizing MPI_Barrier and processor 0 prints out the
received answer.

Part 2: Also, comment on how will you develop the parallel version
Answer
The parallel version of the program can be developed by dividing the task of calculating the factorial of the
input number among the various processors. The processor 0 can compute the factorial of the input
number and return the answer to processor 1. The communication between processor 0 and 1 can be done
using MPI. The computed result can be printed firstly at processor 0 and then the received answer can be
printed at processor 1. By dividing the task of calculating the factorial of the input number among the
different processors. The processor 0 can compute the factorial of the input number and return the answer
to processor 1

Explanation:
By dividing the duty of computing the factorial of the input number among the several processors, a
parallel version of the program may be built. The factorial of the input number can be computed by
processor 0 and returned to processor 1. MPI can be used to communicate between processors 0 and 1.
Processor 0 can publish the computed result first, followed by processor 1 printing the received answer.
The duty of computing the factorial of the input number is divided among the many processors.

You might also like