NPTEL Programming in Java Week 5 Programming Assignment 2 Solution

 This program is to find the GCD (greatest common divisor) of two integers writing a recursive function findGCD(n1,n2). Your function should return -1, if the argument(s) is(are) other than positive number(s).

Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
3
interface GCD {
4
    public int findGCD(int n1,int n2);
5
}
6
//Create a class B, which implements the interface GCD.
7
class B implements GCD
8
{
9
public int findGCD(int n1,int n2)
10
 {
11
12
 if(n2 == 0)
13
 {
14
 return n1;
15
 }
16
 return findGCD(n2,n2%n1);
17
18
 }
19
}
0
public class Question5_2{ 
1
        public static void main (String[] args){ 
2
          B a = new B();   //Create an object of class B
3
            // Read two numbers from the keyboard
4
            Scanner sc = new Scanner(System.in);  
5
             int p1 = sc.nextInt();
6
             int p2 = sc.nextInt();
7
            System.out.print(a.findGCD(p1,p2)); 
8
    } 
9
}
Post a Comment (0)
Previous Question Next Question

You might like