I am trying to create a program for this in C++: Let a and b be the integers so
ID: 674505 • Letter: I
Question
I am trying to create a program for this in C++:
Let a and b be the integers so that both a and b are nonzero. The greatest common divisor of a and b denoted as gcd(a,b) is the largest positive integer that divides both a and b. Your program must contain a function that takes as input two integers and return the gcd of integers.
This is what I have so far, and it compiles, but I have build errors that I don't understand.
#include
#include
using namespace std;
//function prototype
int gcd(int a, int b);
int main()
{
int a, b, c;
//Get user to input two integers
cout << "Enter in a non-zero integer: ";
cin >> a;
cout << "Enter in another integer: ";
cin >> b;
c = gcd(a, b);
cout << "The greatest common divisor of the two non-zero integers are: " << c << endl;
return (a == 0) ? b : gcd(b%a, a);
}
Explanation / Answer
#include<iostream>
#include<cstdlib>
using namespace std;
int gcd(int a,int b)
{
if((a>=b)&&((a%b)==0))
return(b);
else
gcd(b,(a%b));
}
int main()
{
int a,b,c;
cout<<"enter non zero first number:";
cin>>a;
cout<<"enter non zero second number:";
cin>>b;
c=gcd(a,b);
cout<<"nGCD of "<<a<<" and "<<b<<" is "<<c;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.