Programming Examples

Java recursive function to find the gcd of 2 number


Write a Java recursive function which take 2 integer as argument and return the GCD.

Solution:

import java.util.*;
class GCD
{
    public static int gcd(int n1,int n2)
    {
        if(n1==n2)     
        {
            return n1;
        }
        else
        {
            if(n1>n2)
                return gcd(n1-n2,n2);
            else
                return gcd(n1,n2-n1);
        }
    }
    public static void main(String arr[]) 
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter First Number: ");
        int num1=sc.nextInt();
        System.out.println("Enter Second Number: ");
        int num2=sc.nextInt();
        int ans=gcd(num1,num2);
        System.out.println("GCD is "+ans);
    }
}
Output

Enter First Number: 

12

Enter Second Number: 

20

GCD is 4

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz