Solution: GCD of Two Real Numbers Using the Trailing <requires> c

Get an overview of how to find the GCD of two real numbers using the <requires> clause.

We'll cover the following

Solution

As we saw earlier, this solution is based on Euclid’s algorithm. On line 7, we create a concept Number and on line 10 it is required by the function for both the template parameters. As the same concept is required for both template parameters, only floating-point numbers can be passed to the function.

The function gcd() is based on the following observation: if d divides a and d divides b, d divides a - b as well. So, the GCD of a and b is the same as the GCD of a - b and b.

  • If a > b, replace b with a and call the function itself again.
  • Stop if fabs(b) < 0.001. The GCD of a and b, of course, is a. If not, go to the next step. Here, fabs() is a function in the cmath library that returns the absolute value of a number as a float.
  • If a > b, replace a with a - b, then go to the first step.
  • If fabs(b) >= 0.001, replace a with b, replace b with a - floor(a / b) * b, and call the function itself again.

Get hands-on with 1400+ tech skills courses.