GCD recursively

 Description:          The following program takes two numbers as input and determines the Greatest Common Divisor for them using recursion.
                           
Primary Inputs:    Two numbers
Primary Output:    Determine the Greatest Common Divisor for input numbers
Platform Used:      JDK 1.6 with Notepad.
  

import java.io.*;

class GCDRecurse
{
public static void main(String[] args)
{
Console con=System.console();
System.out.print("Enter the first number for finding GCD: ");
int num1=Integer.parseInt(con.readLine());
System.out.print("Enter the second number for finding GCD: ");
int num2=Integer.parseInt(con.readLine());

int gcd=0;
if(num1>num2)
gcd=getGCD(num1,num2,num2);
else
gcd=getGCD(num1,num2,num1);
System.out.println("The GCD for the given numbers is: "+gcd);
}

static int getGCD(int num1,int num2,int gcd)
{
if(gcd==1)
return gcd;
if((num1%gcd==0)&&(num2%gcd==0))
return gcd;
else
gcd=getGCD(num1,num2,gcd-1);
return gcd;
}
}

Rate this post

Leave a Reply