Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write the following program in c++: Each function in your program should have a

ID: 3865121 • Letter: W

Question

Write the following program in c++: Each function in your program should have a header comment as well. Describe its purpose, the parameters and the return value (if any). Use a format similar to:

// Function name:

// Purpose:

// Parameters:

// Return value

The Greatest Common Divisor (gcd) of two or more integers, when at least one of them is not zero, is the largest positive integer that divides the numbers without a remainder. For example, the GCD of 8 and 12 is 4. Write a function named calc_gcd that takes two positive integer arguments and returns the greatest common divisor of those two integers. If the function is passed an argument that is not greater than Zero, then the function should return the value -1 to indicate that an error occurred.

For example,

cout << calc_gcd (8,12) ; // will print 4

cout << calc_gcd(256,625) ; // will print 1

cout << calc_gcd (0,8) ; // will print -1

cout << calc_gcd (10,-2) ; // will print -1

Explanation / Answer

// Function name:calc_gcd()

// Purpose: to compute greatest common divisor

// Parameters: integers x and y

// Return value : gcd

#include <iostream>
#include <cmath>

using namespace std;

int calc_gcd(int x, int y)
    {
        int a,b;
        if(x>y)
        {
            a = x;
            b = y;
        }
        else
        {
            a = y;
            b = x;
        }
        int remainder;
        if(a <= 0 || b <= 0) //return -1 if either a is less than equal to 0 or b is less than equal to 0
        return -1;
        else
      

        while (b != 0)

        {

            remainder = a % b;

            a = b;

            b = remainder;   // remainder becomes b

        }

        return a;
    }

int main()
{
cout << calc_gcd (8,12) ; // will print 4
cout << endl;

cout << calc_gcd(256,625) ; // will print 1
cout << endl;

cout << calc_gcd (0,8) ; // will print -1
cout << endl;

cout << calc_gcd (10,-2) ; // will print -1
cout << endl;

   return 0;
}


Output:

4

1

-1

-1