Greatest Common Divisor (Brute Force Method) A file contains an unknown number o
ID: 3591672 • Letter: G
Question
Greatest Common Divisor (Brute Force Method)
A file contains an unknown number of pairs of positive integer values. One pair per line. You are guaranteed that each member of the pair of numbers will be a positive integer. Your program will learn the name of the file from argv[1]. You are to write a program that will find the greatest common divisor for each pair of numbers.
For this program, you should use a brute force method that will use a loop that will start at the minimum of the two numbers and count down by 1 until the first common divisor of both numbers is found. I do not want you to use Euclid’s method on this one.
What is the greatest common divisor of 50 and 10?
What is the greatest common divisor of 48 and 16?
Explanation / Answer
#include<iostream>
#include<fstream>
using namespace std;
int main(int argc, char **argv){
int a,b;
ifstream fin(argv[1]);
if (!fin){
cout << "Error opening file" << endl;
return 0;
}
while(fin >> a >> b){
int n = b;
while (a % n != 0 && b % n == 0){
n--;
}
cout << "The greatest common divisor of " << a << " and " << b << " is " << n << endl;
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.