********WRITE ONE C++ PROGRAM FOR THIS QUESTION**** Greatest Common Divisor (GCD
ID: 3937261 • Letter: #
Question
********WRITE ONE C++ PROGRAM FOR THIS QUESTION****
Greatest Common Divisor (GCD) Using Recursion:
Write one C++ 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
Explanation / Answer
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int gcd(int n1, int n2)
{
if (n2 != 0)
return gcd(n2, n1 % n2);
else
return n1;
}
int gcd(int a, int b, int c)
{
if(a%c==0 && b%c==0)
return c;
else
return gcd(a,b,c-1);
}
int main(int argc, char * argv[])
{
ifstream myfile("D:/input.txt",ios::in);
cout << " WELCOME TO FIND GCD ";
int a,b,c,d,e;
if(myfile.good()){
string str;
while(getline(myfile,str))
{
istringstream ss(str);
int num1,num2,num3;
if(str.length() <= 5){
while(ss >> num1 >> num2){
cout << "GCD of " << num1 << " and " << num2 << " is " ;
c= gcd(num1,num2);
cout << c << " ";
}
}
else{
while(ss >> num1 >> num2 >> num3){
cout << "GCD of " << num1 << " and " << num2 << " AND " ;
c= gcd(num1,num2);
cout << num3 << " is " ;
d= gcd(c,num3);
cout << d << " ";
}
}
}
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.