Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.4 kB
2
Indexable
Never
#include <stdio.h>
#include <string.h>
#include <mpi.h>
	int main(int argc , char * argv[])
	{
		int my_rank; /* rank of process */
		int p; /* number of process */
		int tag = 0; /* tag for messages */
		char message[1000]; /* storage for message */
		char partOfMessage[1000] ;
		int partMessageSize ;
		char result[1000] ;
		MPI_Status status; /* return status for receive*/
		int choice, add ;
		
		/* Start up MPI */
		MPI_Init( NULL , NULL );
		/* Find out process rank */
		MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
		/* Find out number of process */
		MPI_Comm_size(MPI_COMM_WORLD, &p);
		
		
        
		if( my_rank == 0){
			printf("number of processes is %d",p) ;
			printf("\n");
			printf("enter message: ") ;
			fflush(stdout);
			scanf("%s", message);
			printf("\n enter 1 to encrypt or other number for decrypt: ") ;
			fflush(stdout);
			scanf("%d",&choice) ;
			fflush(stdout) ;
			if(choice == 1)
				add = 3 ;
			else
				add = -3 ;
			int messageSize = strlen(message) ;
			if(p>1)
        		partMessageSize  = messageSize/ (p-1) ;
        	else
        		partMessageSize = messageSize ;
			
			
			
			int remainder = messageSize % (p-1) ;
			
			int index = 0 ;
			int temp = 0 ;
			for(int dest=1; dest<p; dest++){
				if(remainder > 0){
					temp = 1 ;
					remainder-- ;
				}
				else
					temp = 0 ;
				for(int i=0;i<partMessageSize +temp;i++){
					partOfMessage[i] = message[index] ;
					index++ ;
					}
				partOfMessage[partMessageSize+temp] = (char)add ;
				partOfMessage[partMessageSize+temp+1] = '\0' ;
				MPI_Send( partOfMessage, strlen(partOfMessage)+1, MPI_CHAR, dest, tag, MPI_COMM_WORLD);
			}
			index = 0 ;
			for(int source=1; source<p; source++){
				MPI_Recv(partOfMessage, 1000, MPI_CHAR, source, tag, MPI_COMM_WORLD,&status);
				for(int i=0;i<strlen(partOfMessage); i++){
					result[index] = partOfMessage[i] ;
					index++ ;
				}
			}
			result[index] = '\0' ;
			printf("the result is: %s",result) ;
			printf("\n");
			
			
		}
		else{
			
			MPI_Recv(partOfMessage, 1000, MPI_CHAR, 0, tag, MPI_COMM_WORLD,&status);
			char temp[strlen(partOfMessage)] ;
			for(int i=0;i< strlen(partOfMessage)-1; i++)
				temp[i] = partOfMessage[i] + (int)partOfMessage[strlen(partOfMessage)-1] ;
			temp[strlen(partOfMessage)-1] = '\0' ;	
			MPI_Send(temp, strlen(temp)+1, MPI_CHAR, 0, tag, MPI_COMM_WORLD);
			}
		/* shutdown MPI */
		MPI_Finalize();
		return 0;
	}
Leave a Comment