68.0k views
3 votes
Write a program that allows the user to enter as many sets of 2 numbers as needed. For each set of two numbers, compute the Greatest Common Factor (GCF) of the two numbers. The program should do the followings: 1. Allow the user to enter as many sets as needed. 2. After the user enters all the numbers, display each set of two numbers and the GCF for these two numbers. 3. The function to find GCF must be a recursive function. Here is the definition: GCF (n,m)

1 Answer

7 votes

Answer:

#include<iostream>

#include<iomanip>

using namespace std;

//recursive method to find the GCF of two numbers

int GCF(int n, int m){

//case 1, if m<=n and n mod m is 0, then gcf is m

if(m<=n && n%m==0){

return m;

}

//case 2, if n<m, then gcf= GCF(m,n)

if(n<m){

return GCF(m,n);

}

//otherwise, returning GCF(m, n mod m)

return GCF(m,n%m);

}

int main(){

//declaring two arrays of size 100 to store the set of first and second numbers

//and a count

int first[100], second[100], count=0;

char ch;

//asking user if he likes to enter two numbers, reading choice

cout<<" Would you like to enter two numbers? ";

cin>>ch;

//looping as long as ch is 'y' or 'Y'

while(ch=='y' || ch=='Y'){

//prompting and reading numbers to first and second

cout<<endl<<"Please enter two numbers ";

cin>>first[count]>>second[count];

//updating count, asking again

count++;

cout<<" Would you like to enter two numbers? ";

cin>>ch;

}

//left justifying output and printing a blank line

cout<<left<<endl;

//using a field with of 10, printing each column header

cout<<setw(10)<<"First #";

cout<<setw(10)<<"Second #";

cout<<setw(10)<<"GCF"<<endl;

//printing separators

cout<<setw(10)<<"=======";

cout<<setw(10)<<"========";

cout<<setw(10)<<"==="<<endl;

//looping through the arrays

for(int i=0;i<count;i++){

//displaying both numbers and their GCF

cout<<setw(10)<<first[i];

cout<<setw(10)<<second[i];

cout<<setw(10)<<GCF(first[i],second[i])<<endl;

}

return 0;

}

Step-by-step explanation:

Run the program and see the output

User PCoelho
by
4.1k points