Write a recursive method to compute the greatest common divi

Write a recursive method to compute the greatest common divisor of two integers m and n as folic I he gcd(m, n) can be computed recursively as: If m % n is 0, then gcd(m, n) is n. Otherwise gcd(m. n) is gcd(n. m % n) Write a main method that prompts the user to enter two integers, computes their greatest common divisor by calling your gcd method, and displays the result.

Solution

import java.util.*;
import java.lang.*;
import java.io.*;


class GCD
{
   public static int gcd(int m,int n) //recursive function
   {
       if(m % n == 0) return n;   
       else
       return gcd(n,m % n);
      
   }
public static void main(String args[])throws Exception
{
Scanner sc = new Scanner(System.in);
System.out.print(\"Enter the First no : \");
int n1=sc.nextInt();
System.out.print(\"\ Enter the Second no : \");
int n2=sc.nextInt();
  
System.out.print(\"\ GCD = \"+gcd(n1,n2));
}
}

output:

Success time: 0.06 memory: 711680 signal:0

 Write a recursive method to compute the greatest common divisor of two integers m and n as folic I he gcd(m, n) can be computed recursively as: If m % n is 0,

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site