Sunday, May 4, 2008

Extended Euclid Method (Java)


Method untuk aplikasi algoritma Euclid yaitu mencari GCD (Great Common Divisor)
atau FPB (Faktor Persekutuan Terbesar)pada dua bilangan integer

Kemudian Mencari kombinasi linear antara GCD, bilangan1 dan bilangan2
dengan menggunakan algoritma extended euclid

private int[] generateEuclid(int first, int second){
if (first < second){
int swapper = first;
first = second;
second = swapper;
}

if (second == 0){
TAoutput.append("\nGCD : "+first+"\n\n"+"Extended Euclid\n\n");
return new int[] { first, 1, 0 };
}

TAoutput.append(first+" = "+first/second+"."+second+" + "+first%second
+"\n");
int[] prev = generateEuclid(second, first % second);
int gcd = prev[0];
int a = prev[1] - (prev[2]*(first/second)) ;
int b = prev[2];

int swap = a;a=b;b=swap;
swap=first;first=second;second=swap;

TAoutput.append(gcd+" = "+b+"."+first+" + "+a+"."+second+"\n");

return new int[] { gcd, a, b };

}