Hi I need help writing a C++ program to compute the gcd(a,b) and lcm(a,b) using
ID: 3725702 • Letter: H
Question
Hi I need help writing a C++ program to compute the gcd(a,b) and lcm(a,b) using the Euclidean Algorithm.
My professor gave us a pseudocode but I still don't understand. And please show me how to write the code with a way to create a output file as a .txt file. Thanks.
Explanation / Answer
#include<iostream>
#include <fstream>
int gcd(int , int );
using namespace std;
int main()
{
int num1, num2, hcf,prd,lcm;
cout << "Enter two numbers to find GCD using Euclidean algorithm: ";
cin >> num1 >> num2;
hcf = gcd(num1, num2);
if (hcf)
{
prd=num1*num2; // calculating product of 2 numbers
lcm=prd/hcf;
cout << " The GCD of " << num1 << " and " << num2 << " is: " << hcf
<< endl;
cout << " The LCM of " << num1 << " and " << num2 << " is: " << lcm
<< endl;
ofstream out_data("filename.txt"); //openning the file
out_data << " The GCD of " << num1 << " and " << num2 << " is: " << hcf; // writing into the file
out_data << " The LCM of " << num1 << " and " << num2 << " is: " << lcm;
}
else
cout << " Invalid input!!! ";
}
int gcd(int u, int v)
{
return (v != 0) ? gcd(v, u % v) : u;
}