Saltar al contenido principal
ProductosHerramientas de escritorioTASTECADRevisión de planosTASTEFILESGestión de archivosTASTEFTPTransferencia de archivosTASTESSHEspacio de trabajo remotoTASTEZIPCompresión y extracciónTASTEWINMGestión de archivosHerramientas para desarrolladoresTASTECODEEntorno de desarrollo integrado para RustTASTESTUDIOEntorno integrado de desarrollo y pruebasTASTEETLIntegración de datos (ETL)ServidoresTASTEREMOTEServidor de escritorio remotoTASTEGEOServidor geoespacialTASTEMAILEspacio de trabajo de correoInversiónTASTESTOCKAplicación de escritorio de trading automático de accionesEmpezarDescargasDocumentaciónComprarTodos los productos
Marketplace
Noticias
TecnologíaNoticiasNoticias de desarrollo de hoyDocumentaciónLenguajes de programaciónRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks de apps y escritorioTauriFlutterReact NativeElectronAlgoritmosFundamentos de algoritmosAlgoritmos esencialesAlgoritmos avanzadosAlgoritmos prácticos
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparateGuía de la comunidad
ColaboraTransferencia técnicaDesarrollo de sitio webDesarrollo de app de escritorioCanal de lanzamiento y pagosSocio de ventasContacto
ServiciosEscritorio remotoPaquetes de instalación a medida
TASTEDEV
Productos

Herramientas de escritorio

TASTECADAbre planos complejos con ligerezaTASTEFILESSolo los archivos que necesitas, lo más rápido posibleTASTEFTPEl camino más limpio para tus archivosTASTESSHEntre tu servidor y tú, una conexión más sólidaTASTEZIPComprime más rápido, descomprime más seguroTASTEWINMUn gestor de archivos de dos paneles pensado para el teclado

Herramientas para desarrolladores

TASTECODEEdita, compila, depura y prueba apps de Rust en una sola ventanaTASTESTUDIODe la edición a las pruebas remotas y las correcciones con IA aprobadasTASTEETLMueve datos viendo sus valores

Servidores

TASTEREMOTEUn escritorio remoto que funciona en tu propio servidorTASTEGEOUn servidor geoespacial compatible con GeoServer, reconstruido en RustTASTEMAILRecupera el control de tu correo

Inversión

TASTESTOCKTrading automático de acciones según las reglas que tú defines: cuándo y qué

Empezar

DescargasÚltimas versiones de cada productoDocsCómo usar cada productoComprarSuscripciones y licencias perpetuasTodos los productosTodos los productos de un vistazo
Todos los productos
MarketplaceNoticias
Tecnología

Noticias

Noticias de desarrollo de hoyAnuncios oficiales de lenguajes, frameworks, GitHub e IADocumentaciónGuías de lenguajes, frameworks y algoritmos

Lenguajes de programación

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks de apps y escritorioTauriFlutterReact NativeElectron

Algoritmos

Fundamentos de algoritmosAnálisis de complejidad · Ordenamiento · Búsqueda · Estructuras de datos básicas · Árboles y montículosAlgoritmos esencialesRecorrido de grafos · Camino mínimo y árbol generador mínimo · Programación dinámica · Algoritmos voraces · Divide y vencerás · Backtracking (vuelta atrás)Algoritmos avanzadosAlgoritmos de cadenas · Matemáticas y teoría de números · Manipulación de bits · Árboles de segmentos · Union-FindAlgoritmos prácticosEstrategia para entrevistas de código · Caché LRU · Limitación de tasa · Hashing consistente
Toda la documentación de desarrollo
Comunidad
ProyectosDescubre creadores y su trabajoRegistros de desarrolloDecisiones y aprendizajesPromptsInstrucciones reutilizablesProblemas con herramientas de IAProblemas y alternativas de Claude, Codex, GeminiEscaparateResultados terminadosGuía de la comunidadCómo construimos en abierto
Colabora
Transferencia técnicaApps nativas con Rust y eguiDesarrollo de sitio web10 idiomas, cuentas, documentación y descargasDesarrollo de app de escritorioRust y egui, sin WebViewCanal de lanzamiento y pagosFirma, MSI, deb, rpm, AppImage, hashesSocio de ventasRecomiéndanos y gana el 30 %ContactoDesarrollo, alianzas e inversión
Servicios
Escritorio remotoAccede a tu ordenador desde el navegadorPaquetes de instalación a medidaSolo lo necesario, ajustes precargados
Comprar
ES
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Iniciar sesión
Iniciar sesión
TASTEDEV

De pequeñas herramientas a un mejor desarrollo.

support@tastedev.netApoyar a TASTEDEV
ProductosLínea de productosComprarDocsDescargasMarketplaceSoporte
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparate
PolíticasQuiénes somosPolítica de privacidadTérminos de servicioCondiciones de suscripciónReembolsosNormas de la comunidad
CuentaIniciar sesiónRegistrarse
Visitantes
Hoy
Ayer
Vistas totales
Empresa
GXSOFT
Representante
CHOI YOUNG GU
Número de registro mercantil
853-44-00368
Dirección
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Teléfono
+82-10-4404-1523
Correo electrónico
whitecalvin@tastedev.net
Responsable de privacidad
CHOI YOUNG GU

© 2026 TASTEDEVLa información de los productos se basa en fuentes de desarrollo verificadas.Publicado · en mejora

Documentación de Divide y vencerás
Divide y vencerás
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
Debates

Guía de Divide y vencerás · 4/6

Complexity: Recurrences and the Master Theorem

Por ahora, este capítulo solo está disponible en inglés.

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)
¿Tienes preguntas sobre este capítulo?
Capítulo anteriorImplementation: Inversions and Fast PowerCapítulo siguientePractice 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 comentarios

Comentarios destacadosMás recientes primero

Iniciar sesión · Inicia sesión para dejar un comentario.