I'm writing a program that calls a function that calculates and returns both the GCD and LCM of 2 integers. I am having an issue with what's going on in the function as far as the way to code the formulas, and to get it to return both the GCD and LCM...What does it look like I'm doing wrong?
You've got a recursive function without a base case. cout << a; //it returns the GCD No, it prints the GCD. In general you may want to use that value for other things, so it is kind of useless like that.
And if you say that your function returns 1 integer, then you can return just 1 integer.
Ok, I am having an EXTREMELY difficult time trying to figure out why I can't find a way to code that Euclidean Algorithm into my function.. Kapo the function needs to do both GCD and LCM...
kapo is right a function should do one thing well........why must it do two things?
This is one way of getting the gcd:
long gcd(long m,long n)
{
if(m>n)swap(m,n);
assert(n>0);
while(n>0)
{
long r=m%n;
m=n;
n=r;
}
return m;
}
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
usingnamespace std;
void GCD_LCM(int a, int b);
int _tmain(int argc, _TCHAR* argv[])
{
int num1, num2;
char again = 'y';
while (again == 'y' || again =='Y')
{
cout << "Enter first number: "<<endl;
cin>>num1;
cout <<"Enter second number: " <<endl;
cin>> num2;
if (num1<0 || num2<0)
{
num1=abs(num1);
num2=abs(num2);
}
cout<<endl;
cout<< " The GCD and LCM for "<<num1<< " and " <<num2<< " is: ";
GCD_LCM (num1,num2);
cout<<endl;
cout<<endl;
cout<<" Do you want to run this program again? (Y/N)"<<endl;
cin>> again;
cout<< "================================================="<<endl;
cout<<endl;
}
return 0;
}
void GCD_LCM(int a, int b)
{
int q=a/b,r=a%b, GCD1,LCM, num1=0, num2=0;
a=b*q+r;
if (r==0)
GCD1= a;
elsewhile (r!=0)
{
r=a%b;
a=b;
b = r;
}
GCD1= a;
// LCM
// if (GCD1=a)
LCM=( num1 *num2)/18;
// else if (GCD1 = b)
//LCM=(a *b)/GCD1;
cout<< GCD1<< " and "<< LCM<<endl;
}