Is there a better way to get the gcd than using the Euclidean algorithm

醉酒当歌 提交于 2021-01-28 19:20:54

问题


I am trying to find a faster lcm function than I currently have. I tried to look up some better gcd but couldn't find anything that solves the problem.

#include <bits/stdc++.h>
const int MOD = 1000000007;
using namespace std;

long gcd (long a, long b)
{
    if (a == 0) return b;
    return gcd (b % a, a);
}

long lcm (long a, long b)
{
    if (a == 0 || b == 0) return 0;
    return a * b / gcd (a, b);
}

回答1:


The mothed you showed is probably the fastest one, but if you want to avoid recursion, try this, it may be slightly faster.

long gcd (long a, long b)
{
    while (a != 0)
    {
        b %= a;
        if (b == 0)
            return a;
        a %= b;
    }
    return b;
}



回答2:


Though this gcd algorithm is not that bad (and the number of iterations is always small), you can try the Stein's variant, which trades divisions for much faster shifts.

https://en.wikipedia.org/wiki/Binary_GCD_algorithm

Anyway, this does not improve the asymptotic complexity.



来源:https://stackoverflow.com/questions/64071475/is-there-a-better-way-to-get-the-gcd-than-using-the-euclidean-algorithm

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!