8000 Faster Iterative Extended Euclid · Issue #532 · cp-algorithms/cp-algorithms · GitHub
[go: up one dir, main page]

Skip to content
Faster Iterative Extended Euclid #532
Closed
@madhur4127

Description

@madhur4127

As per D. E. Knuth's TAOPC (Vol 1), Extended Euclid (Section 1.2.1, page 13) can be written iteratively, I have seen performance improvement of over 50% when benchmarking it.

Here's a C++ implementation of the idea:

// solves: am + bn = gcd(m,n), m>n
int gcd_fast(int m, int n, int &a, int &b) {
	if (!n) {
		a = 1, b = 0;
		return m;
	}
	int a_ = 1, b_ = 0, c = m, d = n, q = m / n, r = m % n;
	for (a = 0, b = 1; r; q = c / d, r = c % d) {
		c = d;
		d = r;
		tie(a, a_) = make_tuple(a_ - q * a, a);
		tie(b, b_) = make_tuple(b_ - q * b, b);
	}
	return d;
}

I wonder whether this should be added to the tutorial for extended Euclid considering it is a little tricky to prove (mathematical induction btw), but not as tricky as Flows and Li Chao.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0