Lösung Aufgabe 1

/**
	This class calculates PI using various methods.
*/
public class Pi{
	
	private final static int N = 11;
	
	/**
		calculates PI using the formula of Bailey, Borwein, Plouffe
		@return PI
		@see http://de.wikipedia.org/wiki/Bailey-Borwein-Plouffe-Formel
	*/
	public static double valueBBP(){

		double sum = 0;
		
		for(int k=0; k<N; k++){
			sum += 1./Math.pow(16,k) * ( 4./(8.*k+1) - 2./(8.*k+4) - 1./(8.*k+5.) - 1./(8.*k + 6.) );
		}
		
		return sum;
	}
	
	
	/**
		calculates PI using the traditional area formula
		@return PI
		@see http://de.wikipedia.org/wiki/Kreiszahl
	*/
	public static double valueAreaFormula(){
		int r = 50000;
		int hitsCircle = 0;
		double hitsSquare = (2 * r + 1) * (2 * r + 1);
		for (int i = -r; i<= r; i++){
			for (int j = -r; j<=r; j++){
				if(i*i + j*j <= r*r)
					hitsCircle++;
			}
		}
		return 4. * hitsCircle / hitsSquare;
	}	
	
	public static void main(String[] args){
		System.out.println("predefined constant:\t" + Math.PI);
		System.out.println("BBP formula:\t\t" + Pi.valueBBP());
		System.out.println("area formula: \t\t" + Pi.valueAreaFormula());
	}
}

Lösung Aufgabe 2

/**
	This class provides a static function to compute the gcd
*/
public class BinaryEuclid{
	
	/**
		This function computes the greatest common denominator of two
		numbers using the binary Euclidean algorithm
		@param a first number
		@param b second number
		@return the gcd of a and b
		@see http://de.wikipedia.org/wiki/Euklidischer_Algorithmus
	*/
	public static int gcd(int a, int b){
		int m, n;
		//step 0: initialization
		m=a; n=b;
		
		//step 1: binarization
		int k=0;
		while((m%2) == 0 && (n%2) == 0){
			m/=2;
			n/=2;
			k++;
		}
		
		//step 5 ;-)
		while(m>0){ 
			//step 2: make m odd
			while( (m%2)==0 ) m/=2;
			//step 3: occasionally exchange m and n
			if(m<n){
				int tmp=n;
				n=m;
				m=tmp;
			}
		
			//step 4: reduce m
			m-=n;
		}
		
		//return the gcd
		return n * 1<<k; //1<<k == 2^k
		
	}
	
	
	public static void main(String[] args){
		System.out.println("ggT(128, 256) = " + BinaryEuclid.gcd(128,256));
	}
}