Greedy Algorithms & Number Theory

Local choice + CP-র গণিত

~55 min Advanced 25 practice problems Live code

1. Greedy — Local Optimum

Greedy algorithm প্রতিটি step-এ সবচেয়ে ভালো local choice নেয় — backtracking ছাড়াই। Global optimum দেয় শুধু তখনই যখন প্রমাণ-যোগ্য।

Greedy সবসময় কাজ করে না — সঠিক হওয়ার প্রমাণ (সাধারণত exchange argument) থাকতে হবে। ভুল greedy silently wrong answer দেবে।

2. Activity Selection (Classic Greedy)

activity.c
#include <stdio.h>
#include <stdlib.h>

typedef struct { int s, e; } Act;

int cmp(const void *a, const void *b) {
    return ((const Act*)a)->e - ((const Act*)b)->e;
}

int main(void) {
    Act a[] = { {1,4}, {3,5}, {0,6}, {5,7}, {3,9}, {5,9}, {6,10}, {8,11} };
    int n = 8;
    qsort(a, n, sizeof a[0], cmp);

    int last = -1, picked = 0;
    for (int i = 0; i < n; i++) {
        if (a[i].s >= last) {
            printf("(%d, %d)\n", a[i].s, a[i].e);
            last = a[i].e;
            picked++;
        }
    }
    printf("total = %d\n", picked);
    return 0;
}

প্রমাণ: যদি optimal solution আলাদা activity দিয়ে শুরু করে, তাকে আমাদের প্রথম choice-এ swap করা যায় — ফলাফল কমবে না।

3. GCD, LCM, Extended Euclid

gcd_lcm.c
#include <stdio.h>

long gcd(long a, long b) { return b ? gcd(b, a % b) : a; }
long lcm(long a, long b) { return a / gcd(a, b) * b; }

// returns gcd; sets x, y such that a*x + b*y = gcd
long egcd(long a, long b, long *x, long *y) {
    if (b == 0) { *x = 1; *y = 0; return a; }
    long x1, y1;
    long g = egcd(b, a % b, &x1, &y1);
    *x = y1;
    *y = x1 - (a / b) * y1;
    return g;
}

int main(void) {
    printf("gcd(48, 36) = %ld\n", gcd(48, 36));
    printf("lcm(4, 6)   = %ld\n", lcm(4, 6));

    long x, y, g = egcd(30, 18, &x, &y);
    printf("egcd(30, 18): gcd=%ld, x=%ld, y=%ld\n", g, x, y);
    printf("check: 30 * %ld + 18 * %ld = %ld\n", x, y, 30*x + 18*y);
    return 0;
}

4. Sieve of Eratosthenes

sieve.c
#include <stdio.h>
#include <string.h>

#define N 100
int prime[N + 1];

int main(void) {
    for (int i = 0; i <= N; i++) prime[i] = 1;
    prime[0] = prime[1] = 0;

    for (int p = 2; p * p <= N; p++)
        if (prime[p])
            for (int i = p * p; i <= N; i += p) prime[i] = 0;

    for (int i = 2; i <= N; i++) if (prime[i]) printf("%d ", i);
    putchar('\n');
    return 0;
}

O(n log log n) — 10⁷ পর্যন্ত প্রাইম বের করতে দ্রুত।

5. Modular Exponentiation

power_mod.c
#include <stdio.h>

long power_mod(long b, long e, long m) {
    long r = 1; b %= m;
    while (e > 0) {
        if (e & 1) r = r * b % m;
        b = b * b % m;
        e >>= 1;
    }
    return r;
}

int main(void) {
    printf("2^10 mod 1000 = %ld\n", power_mod(2, 10, 1000));
    printf("3^100 mod 1e9+7 = %ld\n", power_mod(3, 100, 1000000007));
    return 0;
}

O(log e)। Cryptography, hashing, combinatorics mod p — সবখানে ব্যবহার।

6. Modular Inverse (Fermat's)

// If p prime and gcd(a, p) = 1, Fermat's little: a^(p-1) ≡ 1 (mod p)
// So   a^(-1) ≡ a^(p-2) (mod p)
long inv = power_mod(a, p - 2, p);

7. Practice Problems

  1. Activity selection — max non-overlapping intervals.
    Activity selection।
    ✨ Show Answer

    Section 2 reference।

  2. Fractional knapsack.
    Fractional knapsack।
    ✨ Show Answer

    value/weight ratio-তে desc sort; capacity ভরাট না হওয়া পর্যন্ত item নিন; শেষ item fractional-ভাবে।

  3. Min number of coins (canonical system).
    Coin change greedy (canonical)।
    ✨ Show Answer

    Coins desc sort; বড় coin যত সম্ভব নিন তারপর ছোট। USD/BDT-র মতো canonical system-এ কাজ করে; arbitrary-তে DP লাগে।

  4. Job sequencing with deadlines.
    Job sequencing।
    ✨ Show Answer

    Profit desc sort; প্রতিটি job-এর জন্য deadline-এর আগের সবচেয়ে late slot নিন (union-find দিয়ে দ্রুত)।

  5. Minimum platforms needed at a station.
    Min platforms।
    ✨ Show Answer

    Arrival এবং departure আলাদা sort; two pointers — arrival < dep হলে platform++ (peak track)।

  6. Huffman coding.
    Huffman coding।
    ✨ Show Answer

    Min-heap-এ frequency। বারবার দুটি smallest extract → merge → push। Tree-এর left = 0, right = 1।

  7. Jump game — can reach end?
    Jump game।
    ✨ Show Answer

    maxReach track করুন; i > maxReach হলে false; maxReach = max(maxReach, i + a[i])।

  8. Jump game II — min jumps.
    Jump game II।
    ✨ Show Answer

    BFS-style: current boundary + far tracking। যখন i == boundary, jumps++, boundary = far।

  9. Gas station circuit.
    Gas station।
    ✨ Show Answer

    Total ≥ 0 হলে answer আছে। tank negative-এ start = i + 1, tank = 0। O(n)।

  10. Reorganize string so no two adjacent are equal.
    String reorganize।
    ✨ Show Answer

    Max-heap-এ frequency। বারবার top 2 নিয়ে একটি করে বসান। Frequency count > (n+1)/2 হলে impossible।

  11. GCD of array.
    Array GCD।
    ✨ Show Answer

    gcd(gcd(a[0], a[1]), a[2]) ... — reduce-fold-এর মতো।

  12. LCM of array (modular).
    Array LCM (modular)।
    ✨ Show Answer

    Overflow এড়াতে lcm(a, b) = a / gcd(a, b) * b; modular-এ modular inverse লাগে।

  13. Extended Euclid.
    Extended Euclid।
    ✨ Show Answer

    Section 3-এর egcd-ই উত্তর।

  14. Linear Diophantine ax + by = c.
    Diophantine।
    ✨ Show Answer

    gcd(a, b) | c না হলে no solution। নতুবা egcd থেকে (x₀, y₀) বের করে c/g দিয়ে scale করুন।

  15. Sieve up to 10⁶; list primes.
    10⁶ পর্যন্ত sieve।
    ✨ Show Answer

    Section 4 reference; শুধু N বদলান।

  16. Count primes ≤ n.
    n-এর নিচে prime count।
    ✨ Show Answer

    Sieve চালিয়ে counter বাড়ান — O(n log log n)।

  17. Smallest prime factor (SPF) of every number up to n.
    প্রতিটি সংখ্যার SPF।
    ✨ Show Answer

    Sieve-এর modified form: if (spf[i] == 0) for j in {i, 2i, ...}: if (spf[j] == 0) spf[j] = i; — factorization O(log n)-এ।

  18. Fast exponentiation (iterative).
    Fast power (iterative)।
    ✨ Show Answer

    Section 5-এর power_mod-ই iterative version — mod সরিয়ে দিলে সাধারণ power।

  19. a^b mod m for large a, b, m.
    Big a^b mod m।
    ✨ Show Answer

    Section 5-এর power_mod-ই উত্তর। a, b, m < 2⁶³ হলে unsigned long long বা __int128 ব্যবহার করুন overflow এড়াতে।

  20. nCr mod p for prime p.
    nCr mod p।
    ✨ Show Answer

    Precompute factorial[] and inv_factorial[] using Fermat's little: nCr = fact[n] * inv_fact[r] * inv_fact[n-r] % p।

  21. Euler's totient function.
    Euler's totient।
    ✨ Show Answer
    long phi(long n) {
        long r = n;
        for (long p = 2; p * p <= n; p++)
            if (n % p == 0) {
                while (n % p == 0) n /= p;
                r -= r / p;
            }
        if (n > 1) r -= r / n;
        return r;
    }
  22. Segmented sieve.
    Segmented sieve।
    ✨ Show Answer

    Range [L, R] (বড়) small prime দিয়ে mark out। Base sieve √R পর্যন্ত; তারপর প্রতিটি prime-এর জন্য [L, R]-এ multiple-গুলো mark।

  23. Miller-Rabin primality test.
    Miller-Rabin।
    ✨ Show Answer

    n - 1 = 2^r · d। a^d বের করুন; r-1 বার square করে 1 বা n-1-এ পৌঁছায় কি না চেক। False witness হলে composite।

  24. Chinese Remainder Theorem.
    CRT।
    ✨ Show Answer

    Pairwise coprime moduli m₁, m₂, ...-এ x ≡ aᵢ (mod mᵢ)-এর unique solution modulo M = Πmᵢ। Extended Euclid ব্যবহার।

  25. Pollard's rho factorization (concept).
    Pollard's rho।
    ✨ Show Answer

    Random walk mod n; cycle-এ gcd factor বের হয়। Miller-Rabin-এর সাথে মিলিয়ে বড় সংখ্যার factorization।

Glossary (শব্দকোষ)

TermMeaningবাংলায়
Greedy AlgorithmMake the locally best choice at each step.প্রতি ধাপে স্থানীয়ভাবে সেরা পছন্দ।
Local OptimumThe best choice at one step.এক ধাপের সেরা পছন্দ।
Global OptimumThe overall best solution.সামগ্রিকভাবে সেরা সমাধান।
Exchange ArgumentProof technique that locally swapping does not improve.স্থানীয় বদল-এ উন্নতি না হওয়ার প্রমাণ-পদ্ধতি।
Activity SelectionClassic greedy — pick non-overlapping intervals.Overlap-হীন interval বাছাই — classic greedy।
Huffman CodingGreedy optimal prefix code.Greedy optimal prefix কোড।
GCDGreatest Common Divisor.সর্বোচ্চ সাধারণ গুণনীয়ক।
LCMLeast Common Multiple — a*b/gcd(a,b).সর্বনিম্ন সাধারণ গুণিতক।
Euclidean AlgorithmComputes GCD via repeated remainder.বারবার remainder নিয়ে GCD।
Modular ArithmeticArithmetic over remainders mod m.m দিয়ে ভাগ-শেষ-এর গণিত।
Prime NumberAn integer > 1 with only 1 and itself as divisors.১ ও নিজে ছাড়া অন্য কোনো গুণনীয়ক নেই।
Sieve of EratosthenesO(n log log n) algorithm to list all primes ≤ n.n পর্যন্ত prime খুঁজে বের করার দ্রুত পদ্ধতি।
Modular ExponentiationFast a^b mod m in O(log b).O(log b)-তে a^b mod m।
Modular InverseThe number x such that a·x ≡ 1 (mod m).a·x ≡ 1 (mod m) পূরণকারী x।
Fermat's Little TheoremIf p prime and gcd(a,p)=1, then a^(p-1) ≡ 1 (mod p).Prime mod-এ inverse বের করার সূত্র।

Summary — Module 34

Greedy দ্রুত কিন্তু প্রমাণ লাগে। Number theory toolkit: GCD, sieve, modular exponentiation, inverse — competitive programming ও cryptography-র মূল।

Next Module → CP Tactics & Contests।