Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCD function in c++ sans cmath library

I'm writing a mixed numeral class and need a quick and easy 'greatest common divisor' function. Can anyone give me the code or a link to the code?

like image 700
Connor Black Avatar asked Sep 10 '25 01:09

Connor Black


2 Answers

The libstdc++ algorithm library has a hidden gcd function (I'm using g++ 4.6.3).

#include <iostream>
#include <algorithm>

int main()
{
  std::cout << std::__gcd(100,24); // print 4
  return 0;
}

You are welcome :)

UPDATE: As @chema989 noted it, in C++17 there is std::gcd() function available with <numeric> header.

like image 199
Tomasz Posłuszny Avatar answered Sep 12 '25 16:09

Tomasz Posłuszny


I'm tempted to vote to close -- it seems difficult to believe that an implementation would be hard to find, but who knows for sure.

template <typename Number>
Number GCD(Number u, Number v) {
    while (v != 0) {
        Number r = u % v;
        u = v;
        v = r;
    }
    return u;
}

In C++ 17 or newer, you can just #include <numeric>, and use std::gcd (and if you care about the gcd, chances are pretty fair that you'll be interested in the std::lcm that was added as well).

like image 42
Jerry Coffin Avatar answered Sep 12 '25 15:09

Jerry Coffin