reatest Common Divisor GCD Using Recursion Write one program
reatest Common Divisor (GCD) Using Recursion:
Write one program to satisfy the following:
1. Write a program that will read each line from A1.txt.
2. Show the GCD of the numbers in each line of the input file (using recursion) in a output file B1.txt.
3. Each line in A1.txt will correspond to each line of B1.txt.
*****Note: A single line of A1.txt may contain two/three integer numbers. First three lines are given as sample.
A1.txt :
Sample input
5 7
12 15
80 40 100
Sample Output Format:
1
3
20
Solution
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;
public class GCDRecursion {
/**
* method to find gcd of m and n
*
* @param m
* @param n
* @return
*/
static int gcd(int m, int n) {
if (n == 0)
return m;
else if (n > m)
return gcd(n, m);
else
return gcd(n, m % n);
}
/**
* @param args
*/
public static void main(String[] args) {
Scanner scanner = null;
try {
File file = new File(\"B1.txt\");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
scanner = new Scanner(new File(\"A1.txt\"));
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
while (scanner.hasNext()) {
String line = scanner.nextLine();
String[] lineArr = line.split(\" \");
int gcdValue;
if (lineArr.length == 2) {
gcdValue = gcd(Integer.parseInt(lineArr[0]),
Integer.parseInt(lineArr[1]));
} else {
gcdValue = gcd(
Integer.parseInt(lineArr[2]),
gcd(Integer.parseInt(lineArr[0]),
Integer.parseInt(lineArr[1])));
}
bw.write(gcdValue + \"\ \");
}
bw.close();
} catch (Exception e) {
// TODO: handle exception
} finally {
scanner.close();
}
}
}
A1.txt
5 7
12 15
80 40 100
6 18
70 100 25
30 9
72 48 16
10 15
16 20
128 48 24
B1.txt
1
3
20
6
5
3
8
5
4
8

