ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

Java Source code on Printing the Greatest Common Divisor (GCD) using Recursion

Updated on November 1, 2013

Get A Website Plus a Free Domain Name in Just 1 Hour!

Bring the new technology in your hands! Share your skills, improve and impress. Get Your Own Website and a Free Domain Name Here!

Below is the Java sample code on printing the GCD of the 2 numbers in recursion. The GCD recursive methods is quite an easy problem to program if you know its recursive definition. Since recursion is basically has a base case and general case, the program will stop on looping if it meets the condition of the base case and return a value of the general case if not. To have a glimpse of the recursive formula, here it is for you to evaluate and see how I transform it into java language.

GCD Recursive Definition:

Given two integers x and y

		{ x if y==0

GCD(x, y) =

		{ y if y != 0

Below is the following code for the recursive definition above.

Java Source Code on Printing the Greatest Common Divisor or GCD in Recursion

//java class

public class GCD
    public static int gcd(int num1, int num2)
        if(num2 == 0)
            return num1;
            return gcd(num2, num1%num2);


//main class

import java.util.Scanner;

public class Main

    public static void main(String[] args)
       Scanner input = new Scanner(;

      System.out.print("Enter the base number: ");
      int num1 = input.nextInt();

      System.out.print("Enter the power: ");
      int num2 = input.nextInt();

      GCD access = new GCD();

      System.out.print("The GCD of 2 numbers is: " + access.gcd(num1, num2));



Here is the sample output of the program

Sample Output:

Enter the base number: 100

Enter the power: 45

The GCD of 2 numbers is: 5

Sample Output 2:

Enter the base number: 6

Enter the power: 8

The GCD of 2 numbers is: 2


    0 of 8192 characters used
    Post Comment

    • profile image

      Deepankar 5 years ago

      if the second number(num2) is comparatively larger than the first number(num1). suppose, num1=30 and num2=90 then what will this function call return

      gcd(90,30%90); If the numbers is swapped then its perfectly fine.