Data Structures and Algorithms • C# examples
GCD, Sieve of Eratosthenes, and Fast Exponentiation
Apply number-theory techniques to divisibility, prime generation, and modular powers.
Concept
Euclid’s algorithm repeatedly replaces a pair with (b, a mod b). The Sieve marks multiples to find primes up to a bound. Exponentiation by squaring halves the exponent at each step and is especially useful for modular arithmetic, where intermediate products may need a wider numeric type.
How to approach it
Handle zero and sign conventions for GCD, start sieving at p², and use a safe multiplication strategy for modular products.
Complexity
GCD O(log min(a,b)); sieve O(n log log n); power O(log exponent) multiplications.
C# example
static long Gcd(int a, int b)
{
long x = Math.Abs((long) a), y = Math.Abs((long) b);
while (y != 0) (x, y) = (y, x % y);
return x;
}
Expected result or behavior
Each remainder step reduces the second argument until the greatest common divisor remains.
Practice exercise
Extend exponentiation by squaring to compute a^e mod m without overflow for your chosen numeric bounds.
Key takeaway: Small mathematical invariants often yield algorithms with logarithmic or near-linear cost.