问题
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