170k views
2 votes
Write a program that applies the Euclidean algorithm to find the greatest common divisor of two integers. Input should be two integers a and b and output should be the greatest common divisor of a and b. Test your program with several examples using both positive and negative values for a and b.

User Elgoog
by
5.3k points

1 Answer

0 votes

Answer:

// here is code in c++.

#include <bits/stdc++.h>

using namespace std;

// function that return greatest common divisor

int g_c_d(int num1, int num2)

{

if (num1 == 0)

return num2;

return g_c_d(num2 % num1, num1);

}

// main function

int main()

{

// variables

int num1,num2;

cout<<"enter two numbers:";

// read two numbers from user

cin>>num1>>num2;

// call the function and print the gcd of both

cout<<"greatest common divisor of "<<num1<<" and "<<num2<<" is "<<g_c_d(num1.num2)<<endl;

}

Step-by-step explanation:

Read two numbers from user and assign them to variables "num1" and "num2".Call the function g_c_d() with parameter "num1" and "num2".According to Euclidean algorithm, if we subtract smaller number from the larger one the gcd will not change.Keep subtracting the smaller one then we find the gcd of both the numbers.So the function g_c_d() will return the gcd of both the numbers.

Output:

enter two numbers:5 9

greatest common divisor of 5 and 9 is 1

enter two numbers:-25 15

greatest common divisor of -25 and 15 is 5

User FalconNL
by
6.5k points