Vai al contenuto principale
ProdottiStrumenti desktopTASTECADVisualizzazione disegniTASTEFILESGestione fileTASTEFTPTrasferimento fileTASTESSHSpazio di lavoro remotoTASTEZIPCompressione ed estrazioneTASTEWINMGestione fileStrumenti per sviluppatoriTASTECODEAmbiente di sviluppo integrato per RustTASTESTUDIOAmbiente integrato di sviluppo e testTASTEETLIntegrazione dati (ETL)ServerTASTEREMOTEServer di desktop remotoTASTEGEOServer geospazialeTASTEMAILSpazio di lavoro emailInvestimentiTASTESTOCKApp desktop di trading automatico azionarioIniziaDownloadDocumentazioneAcquistaTutti i prodotti
Marketplace
Notizie
TecnologiaNotizieNotizie di sviluppo di oggiDocumentazioneLinguaggi di programmazioneRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFramework frontend webNext.jsReactVue.js · NuxtSvelteKitAngularFramework serverSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFramework per app e desktopTauriFlutterReact NativeElectronAlgoritmiBasi degli algoritmiAlgoritmi fondamentaliAlgoritmi avanzatiAlgoritmi pratici
CommunityProgettiLog di sviluppoPromptProblemi degli strumenti di IAVetrinaGuida alla community
CollaboraTrasferimento tecnicoRealizzazione del sito webRealizzazione di app desktopPipeline di rilascio e pagamentoPartner commercialeContatti
ServiziDesktop remotoPacchetti di installazione su misura
TASTEDEV
Prodotti

Strumenti desktop

TASTECADApri con leggerezza anche i disegni più complessiTASTEFILESSolo i file che servono, alla massima velocitàTASTEFTPLa via più ordinata per i tuoi fileTASTESSHUn legame più solido tra te e i tuoi serverTASTEZIPComprimi più veloce, estrai più sicuroTASTEWINMUn file manager a due pannelli pensato per la tastiera

Strumenti per sviluppatori

TASTECODEModifica, compila, esegui il debug e testa app Rust in un'unica finestraTASTESTUDIODalla modifica ai test remoti e alle correzioni IA approvateTASTEETLSposta i dati guardando i valori

Server

TASTEREMOTEUn desktop remoto che gira sul tuo serverTASTEGEOUn server geospaziale compatibile con GeoServer, ricostruito in RustTASTEMAILRiprendi il controllo della tua posta

Investimenti

TASTESTOCKTrading automatico azionario secondo le regole che decidi tu: quando e che cosa

Inizia

DownloadUltime versioni di ogni prodottoDocsCome usare ogni prodottoAcquistaAbbonamenti e licenze perpetueTutti i prodottiTutti i prodotti a colpo d’occhio
Tutti i prodotti
MarketplaceNotizie
Tecnologia

Notizie

Notizie di sviluppo di oggiAnnunci ufficiali su linguaggi, framework, GitHub e IADocumentazioneGuide a linguaggi, framework e algoritmi

Linguaggi di programmazione

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Framework

Framework frontend webNext.jsReactVue.js · NuxtSvelteKitAngular
Framework serverSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Framework per app e desktopTauriFlutterReact NativeElectron

Algoritmi

Basi degli algoritmiAnalisi della complessità · Ordinamento · Ricerca · Strutture dati di base · Alberi e heapAlgoritmi fondamentaliVisita dei grafi · Cammini minimi e alberi ricoprenti · Programmazione dinamica · Algoritmi greedy · Divide et impera · BacktrackingAlgoritmi avanzatiAlgoritmi sulle stringhe · Matematica e teoria dei numeri · Manipolazione dei bit · Alberi di segmenti · Union-FindAlgoritmi praticiStrategia per colloqui di programmazione · Cache LRU · Rate limiting · Hashing consistente
Tutta la documentazione di sviluppo
Community
ProgettiScopri sviluppatori e lavoriLog di sviluppoDecisioni e lezioni appresePromptIstruzioni riutilizzabiliProblemi degli strumenti di IAProblemi e alternative di Claude, Codex, GeminiVetrinaRisultati completatiGuida alla communityCome sviluppiamo in modo aperto
Collabora
Trasferimento tecnicoApp native in Rust ed eguiRealizzazione del sito web10 lingue, account, documentazione e downloadRealizzazione di app desktopRust ed egui, senza WebViewPipeline di rilascio e pagamentoFirma, MSI, deb, rpm, AppImage, hashPartner commercialeConsigliaci e ricevi il 30%ContattiSviluppo, partnership e investimenti
Servizi
Desktop remotoRaggiungi il tuo computer dal browserPacchetti di installazione su misuraSolo il necessario, impostazioni precaricate
Acquista
IT
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Accedi
Accedi
TASTEDEV

Dai piccoli strumenti a uno sviluppo migliore.

support@tastedev.netSostieni TASTEDEV
ProdottiGamma di prodottiAcquistaDocsDownloadMarketplaceAssistenza
CommunityProgettiLog di sviluppoPromptProblemi degli strumenti di IAVetrina
NormeChi siamoInformativa sulla privacyTermini di servizioCondizioni di abbonamentoRimborsiLinee guida della community
AccountAccediRegistrati
Visitatori
Oggi
Ieri
Visualizzazioni totali
Società
GXSOFT
Rappresentante
CHOI YOUNG GU
Numero di registrazione
853-44-00368
Indirizzo
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Telefono
+82-10-4404-1523
E-mail
whitecalvin@tastedev.net
Responsabile privacy
CHOI YOUNG GU

© 2026 TASTEDEVLe informazioni sui prodotti si basano su fonti di sviluppo verificate.Rilasciato · in miglioramento

Documentazione di Divide et impera
Divide et impera
Divide and Conquer: Core ConceptsHow It Works: Step-by-Step TracesImplementation: Inversions and Fast PowerComplexity: Recurrences and the Master TheoremPractice ProblemsDivide and Conquer in the Real World
Discussioni

Guida a Divide et impera · 4/6

Complexity: Recurrences and the Master Theorem

Per ora questo capitolo è disponibile solo in inglese.

The running time of a divide-and-conquer algorithm is described by a recurrence: the cost of a call equals the cost of its recursive calls plus the cost of dividing and combining. This chapter shows how to solve such recurrences and compares the classic algorithms with their alternatives.

Writing a recurrence

If an algorithm splits an input of size n into a subproblems of size n/b and spends f(n) on dividing and combining, then T(n) = a * T(n/b) + f(n). Merge sort makes two half-size calls and merges in linear time, so T(n) = 2T(n/2) + O(n).

Draw the recursion tree to see the total. Merge sort's tree has log2 n levels and every level does n work in total:

level 0:  n                          -> n
level 1:  n/2  n/2                   -> n
level 2:  n/4  n/4  n/4  n/4         -> n
...       (log2 n levels)
total:    n * log2 n = O(n log n)

The master theorem

For T(n) = a * T(n/b) + f(n) with a >= 1 and b > 1, compare f(n) with n^c, where c = log_b(a) is the critical exponent: the number of leaves of the tree grows like n^c.

  1. If f(n) = O(n^d) for some d < c, the leaves dominate: T(n) = Θ(n^c).
  2. If f(n) = Θ(n^c * (log n)^k) for some k >= 0, every level costs about the same: T(n) = Θ(n^c * (log n)^(k+1)).
  3. If f(n) = Ω(n^d) for some d > c, and a * f(n/b) <= q * f(n) for some constant q < 1, the root dominates: T(n) = Θ(f(n)).
AlgorithmRecurrencec = log_b aCaseResult
Binary searchT(n/2) + O(1)02O(log n)
Fast exponentiationT(e/2) + O(1)02O(log e) multiplications
Merge sort, inversions2T(n/2) + O(n)12O(n log n)
Closest pair2T(n/2) + O(n)12O(n log n)
Karatsuba3T(n/2) + O(n)
Domande su questo capitolo?
Capitolo precedenteImplementation: Inversions and Fast PowerCapitolo successivoPractice Problems
about 1.585
1
O(n^1.585)
Naive matrix multiplication8T(n/2) + O(n^2)31O(n^3)
Strassen7T(n/2) + O(n^2)about 2.8071O(n^2.807)
Quickselect, averageT(n/2) + O(n)03O(n) expected

Quickselect's worst case, T(n) = T(n - 1) + O(n) = O(n^2), does not fit the theorem because the subproblem shrinks by one element instead of a constant factor.

Karatsuba: three products instead of four

Split two numbers at m digits: x = x1 * 10^m + x0 and y = y1 * 10^m + y0. Then x * y = z2 * 10^(2m) + z1 * 10^m + z0, with z2 = x1 * y1, z0 = x0 * y0 and z1 = x1 * y0 + x0 * y1. Computing z1 directly needs two more products, giving 4T(n/2) and therefore O(n^2), no better than schoolbook multiplication. Karatsuba's trick is z1 = (x1 + x0) * (y1 + y0) - z2 - z0, which needs only one extra product. Three subproblems give O(n^log2(3)), about O(n^1.585).

def karatsuba(x, y):
    """Product of two non-negative integers with three recursive products."""
    if x < 10 or y < 10:
        return x * y
    m = max(len(str(x)), len(str(y))) // 2
    x1, x0 = divmod(x, 10 ** m)
    y1, y0 = divmod(y, 10 ** m)
    z2 = karatsuba(x1, y1)
    z0 = karatsuba(x0, y0)
    z1 = karatsuba(x1 + x0, y1 + y0) - z2 - z0
    return z2 * 10 ** (2 * m) + z1 * 10 ** m + z0

print(karatsuba(1234, 5678) == 1234 * 5678)  # True

Closest pair: why the strip is cheap

To find the closest pair among n points, sort them by x, split at the median x, and solve both halves to get d, the smaller of the two best distances. A closer pair must cross the dividing line, so both of its points lie in a strip of width 2d around it. Sort the strip by y; within that order each point only needs to be compared with a constant number of following points (at most 7), because more points than that cannot fit in a d by 2d box while staying d apart. The combine step is O(n) if the halves are merged by y as in merge sort, so T(n) = 2T(n/2) + O(n) = O(n log n). Re-sorting the strip at every level instead costs O(n log^2 n).

Counting the work

Counting operations is a quick way to check an analysis:

def count_mults(e):
    """Multiplications done by recursive fast power for exponent e."""
    if e == 0:
        return 0
    return count_mults(e // 2) + (2 if e % 2 else 1)

for e in (10, 1000, 10**6, 10**18):
    print(e, "naive:", max(e - 1, 0), "fast:", count_mults(e))

For e = 10^18 the naive method needs about 10^18 multiplications; fast power needs fewer than 120.

Comparison with alternatives

ProblemSimple approachDivide and conquerOther options
Counting inversionsAll pairs, O(n^2)Merge sort, O(n log n)Fenwick tree, O(n log n)
Power b^eRepeated multiplication, O(e)Fast power, O(log e)Built-in pow
k-th smallestSort, O(n log n)Quickselect, O(n) expectedMedian of medians, O(n) worst case; heap, O(n log k)
Big-number productSchoolbook, O(n^2)Karatsuba, O(n^1.585)FFT-based, about O(n log n)
Closest pairAll pairs, O(n^2)Strip method, O(n log n)Grid hashing, O(n) expected

Space matters too. Merge sort needs O(n) extra memory for merging, while recursion depth is O(log n) for balanced splits. Quickselect works in place but can recurse O(n) deep with bad pivots, which is why the loop form in the previous chapters is safer in Python.

Summary

  • Write T(n) = a * T(n/b) + f(n) and compare f(n) with n^log_b(a).
  • Equal cost on every level adds a log n factor; otherwise the leaves or the root dominate.
  • Karatsuba wins by turning four subproblems into three.
  • Shrinking by a constant factor matters: shrinking by one element gives quadratic time.

0 commenti

Commenti principaliPrima i più recenti

Accedi · Accedi per lasciare un commento.