#include "stdafx.h"

#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>

#include <math.h>

#include <windows.h>

#include <time.h>

///////////////////////////////////////////////////////////////////////////
// Konstanten
///////////////////////////////////////////////////////////////////////////


#define root 0

double f(double x) {
	return 3*x*x + 2*x +1;
}


int main(int argc, char *argv[])
{
    int myPid;
    int numprocs;
	int i, j;
	double s, g_s, x, xa, xe, y, h;

	
    MPI_Init(&argc,&argv);

	   // Anzahl der Prozesse
    MPI_Comm_size(MPI_COMM_WORLD,&numprocs);
   
	   // meine eigene ID
	MPI_Comm_rank(MPI_COMM_WORLD,&myPid);
    
	
	

	//printf("myPid %d  N %u \n", myPid, zahl);
	if (myPid==root) {
		xa = 10.0;
		xe = 30.0;

		h = (xe-xa) / numprocs;
		h = 0.0001;
	}

    // An alle Client und Master eine Botschaft senden, wieviele n
    MPI_Bcast(&xa, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
    MPI_Bcast(&xe, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
    MPI_Bcast(&h, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);


	x = xa;
	for (j=1; j<=myPid; j++) {
		x+=h;
	}
	
	printf("Pid: %d   h: %f  x: %f\n",myPid, h, x);

	s =0.0;
	g_s = 0.0;
	while (x<xe) {
		if (myPid==43) {
			printf("\n\nx %f\n", x);
		}
		y = f(x);
		s += y*h;
		//s+=myPid;
		for (i=0; i<numprocs; i++) {
			x += h;
		}

	}
	printf("Pid: %d   h: %f  Summe: %f\n",myPid, h, s);
	

	MPI_Reduce(&s, &g_s, 1, MPI_DOUBLE, MPI_SUM, root, MPI_COMM_WORLD);
	if (myPid==root) {
		printf("\n\nIntegral lautet %f\n", g_s);
	}

    MPI_Finalize();
	return 0;
}

