From d79e122e044e02c1544992c8adc0f7aa8c4f8f91 Mon Sep 17 00:00:00 2001 From: "exercism-solutions-syncer[bot]" <211797793+exercism-solutions-syncer[bot]@users.noreply.github.com> Date: Sat, 20 Jun 2026 20:26:45 +0000 Subject: [PATCH] [Sync Iteration] cpp/nth-prime/1 --- solutions/cpp/nth-prime/1/nth_prime.cpp | 41 +++++++++++++++++++++++++ solutions/cpp/nth-prime/1/nth_prime.h | 5 +++ 2 files changed, 46 insertions(+) create mode 100644 solutions/cpp/nth-prime/1/nth_prime.cpp create mode 100644 solutions/cpp/nth-prime/1/nth_prime.h diff --git a/solutions/cpp/nth-prime/1/nth_prime.cpp b/solutions/cpp/nth-prime/1/nth_prime.cpp new file mode 100644 index 0000000..509a0ab --- /dev/null +++ b/solutions/cpp/nth-prime/1/nth_prime.cpp @@ -0,0 +1,41 @@ +#include "nth_prime.h" +#include + +namespace nth_prime { + +// Función auxiliar +bool is_prime(int num) { + if (num <= 1) return false; + if (num <= 3) return true; // 2 y 3 son primos + if (num % 2 == 0 || num % 3 == 0) return false; // Filtramos múltiplos de 2 y 3 + + // Bucle ultra avanzando de 6 en 6 + for (int i = 5; i * i <= num; i += 6) { + if (num % i == 0 || num % (i + 2) == 0) { + return false; + } + } + return true; +} + +int nth(int n) { + // Validación + if (n <= 0) { + throw std::domain_error("El argumento debe ser mayor o igual a 1."); + } + + int prime_count = 0; // Cuántos primos llevamos encontrados + int current_num = 1; // Número que estamos probando en cada iteración + + // 2. Bucle de búsqueda + while (prime_count < n) { + current_num++; + if (is_prime(current_num)) { + prime_count++; + } + } + + return current_num; // Este es el n-ésimo primo +} + +} \ No newline at end of file diff --git a/solutions/cpp/nth-prime/1/nth_prime.h b/solutions/cpp/nth-prime/1/nth_prime.h new file mode 100644 index 0000000..a98c544 --- /dev/null +++ b/solutions/cpp/nth-prime/1/nth_prime.h @@ -0,0 +1,5 @@ +#pragma once + +namespace nth_prime { + int nth(int n); +} \ No newline at end of file