GCD function in c++ sans cmath library

前端 未结 5 979
悲哀的现实
悲哀的现实 2020-12-14 01:54

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?

5条回答
  •  囚心锁ツ
    2020-12-14 02:45

    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 
    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 , 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).

提交回复
热议问题