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
, replaceb
witha
and call the function itself again. - Stop if
fabs(b) < 0.001
. The GCD ofa
andb
, of course, isa
. If not, go to the next step. Here,fabs()
is a function in thecmath
library that returns the absolute value of a number as a float. - If
a > b
, replacea
witha - b
, then go to the first step. - If
fabs(b) >= 0.001
, replacea
withb
, replaceb
witha - floor(a / b) * b
, and call the function itself again.
Get hands-on with 1400+ tech skills courses.