Question: write a code in c++ do following Euclids algorithm to calculate the greatest common divisor (GCD) of two positive integers was presented in class. The
write a code in c++ do following
Euclids algorithm to calculate the greatest common divisor (GCD) of two positive integers was presented in class. The code was given as follows long gcd_euclid(long a, long b) { if (a < b) { return gcd_euclid(b,a); } long c = (a%b); if (c == 0) return b; else if (c == 1) return 1; return gcd_euclid(b,c); } 1.1.1 Modify the code to return 0 to guard against invalid inputs a < 0 or b < 0. Excel has a function gcd(number1, number2). Try it. Observe that Excel will complain if you enter negative inputs. What if either a or b equal zero? If a = 10 and b = 0, then Excel returns gcd(10, 0) = 10. Something to think about: if a > 0 and b = 0, then a obviously divides a, and logically, it also divides zero (the remainder is zero!). Modify the above code so that if a = 0 then return gcd = b, and if b = 0 then return gcd = a. Obviously if a = b = 0 then gcd = 0. You can check by comparing your function output to the Excel output, for arbitrary values of a and b. 1.1.2 The lowest common multiple (LCM) of two positive integers is related to the GCD via LCM(a, b) GCD(a, b) = ab . Write a function with signature long LCM(long a, long b) to compute the LCM of two integers a, b. If a 0 or b 0, then return 0. 2 1.2 Convert decimal to binary, decimal to hex This function inputs a positive integer in decimal, and outputs an array (vector) with digits in any base from 2 through 16. int dec_to_base(int a, int base, std::vector & digits) { char alphanum[16] = {0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F}; digits.clear(); if ((base < 2) || (base > 16)) return 1; // fail if (a < 0) return 1; // fail if (a == 0) { digits.push_back(alphanum[0]); return 0; } while (a > 0) { int rem = a % base; char c = alphanum[rem]; digits.push_back(c); a /= base; } std::reverse(digits.begin(), digits.end()); // reverse the digits return 0; } Note that the output vector is char not int because the digits are alphanumeric. The function return type is int not void because we test for bad inputs: the function returns 0 for success and 1 for failure. The output elements are ordered so that if we print as follows, we get the digits in the base for (int i = 0; i < (int) digits.size(); ++i) { std::cout << digits[i]; } std::cout << std::endl; 1.2.1 Try this out for sample inputs such as a = 106 (you should get 6A), etc. Excel has a function dec2hex. You can check by comparing the function output to the Excel output. If a = 1, Excel returns dec2hex(-1) = FFFFFFFFFF (on a 32-bit computer). Let us skip negative inputs. The lesson is that people who write industrial strength commercial products need to guard against all cases.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
