Showing posts with label Gcd_Algorithm. Show all posts
Showing posts with label Gcd_Algorithm. Show all posts

Thursday, March 4, 2010

Gcd_Algorithm

public class Gcd_Algorithm
{
//Method Iterator for Great Common Divisor
public static long iteration (long a, long b)
{
int gcd = 1;
int k = 1;

while (k <= a && k <= b)
{
if (a % k == 0 && b % k == 0)
gcd = k;
k++;
}

System.out.print("\nGreat Common Divisor in iteration method : " + gcd);
return gcd;
}








//Method Recursive
public static long recursion (long a, long b)
{
long gcd = 0;
long r = 0;

a = Math.abs (a);
b = Math.abs (b);
if (b == 0)
{
gcd = a; //if n == 0, then m = gcd
System.out.println ("\nGreat Common Divisor in recursive method : " + gcd);
}
else
{
gcd = recursion(b, a % b); //invoke recursive method, and return value n
}

return gcd;
}
}






import java.util.*;
public class Main
{
public static void main (String [] args)
{
Gcd_Algorithm gcd = new Gcd_Algorithm();

Scanner myscanner = new Scanner (System.in);
System.out.print ("Please enter value of a:");
long a = myscanner.nextInt(); //input m value

System.out.print ("Please enter value of b:");
long b = myscanner.nextInt(); //input n value

gcd.iteration(a, b); //invoke to iteration method
gcd.recursion(a, b); //invoke to recursion method
}
}
OUTPUT
--------------------Configuration: --------------------
Please enter value of a:3
Please enter value of b:5

Great Common Divisor in iteration method : 1
Great Common Divisor in recursive method : 1

Process completed.