K-ésimo número primo mayor que N

Dado un número N, la tarea es imprimir el K-ésimo número primo mayor que N. 
Nota: N y K se dan de tal manera que las respuestas siempre son menores que 10^6. 
Ejemplos: 
 

Input: N = 5, K = 5
Output: 19

Input: N = 10, K = 3
Output: 17

Una solución simple para este problema es iterar desde n+1 hasta 10^6 y para cada número, verificar si es primo e imprimir el K-ésimo número primo. Esta solución se ve bien si solo hay una consulta. Pero no es eficiente si hay varias consultas.
Una solución eficiente para este problema es generar todos los números primos menores que 10 ^ 6 usando la criba de Eratóstenes e iterar desde n+1 hasta 10 ^ 6 y luego imprimir el número primo Kth. 
 

C++

// CPP program to print the Kth prime greater than N
#include <bits/stdc++.h>
using namespace std;
 
// set the MAX_SIZE of the array to 10^6
const int MAX_SIZE = 1e6;
 
// initialize the prime array
bool prime[MAX_SIZE + 1];
 
void sieve()
{
 
    // set all numbers as prime for time being
    memset(prime, true, sizeof(prime));
 
    for (int p = 2; p * p <= MAX_SIZE; p++) {
 
        // if prime[p] is not changed, then it is a prime
        if (prime[p] == true) {
 
            // update all multiples of p
            for (int i = p * p; i <= MAX_SIZE; i += p)
                prime[i] = false;
        }
    }
}
// Function to find the kth prime greater than n
int kthPrimeGreaterThanN(int n, int k)
{
 
    int res = -1;
    // looping through the numbers greater than n
    for (int i = n + 1; i < MAX_SIZE; i++) {
 
        // decrement k if i is prime
        if (prime[i] == true)
            k--;
 
        // store the kth prime greater than n
        if (k == 0) {
            res = i;
            break;
        }
    }
 
    return res;
}
 
// Driver code
int main()
{
 
    sieve();
    int n = 2, k = 15;
 
    // Print the kth prime number greater than n
    cout << kthPrimeGreaterThanN(n, k);
    return 0;
}

Java

// Java program to print the
// Kth prime greater than N
import java.util.*;
 
class GFG
{
 
// set the MAX_SIZE of the array to 10^6
static int MAX_SIZE = (int) 1e6;
 
// initialize the prime array
static boolean []prime = new boolean[MAX_SIZE + 1];
 
static void sieve()
{
 
    // set all numbers as prime for time being
    Arrays.fill(prime, true);
 
    for (int p = 2; p * p <= MAX_SIZE; p++)
    {
 
        // if prime[p] is not changed,
        // then it is a prime
        if (prime[p] == true)
        {
 
            // update all multiples of p
            for (int i = p * p;
                     i <= MAX_SIZE; i += p)
                prime[i] = false;
        }
    }
}
 
// Function to find the kth prime greater than n
static int kthPrimeGreaterThanN(int n, int k)
{
 
    int res = -1;
     
    // looping through the numbers greater than n
    for (int i = n + 1; i < MAX_SIZE; i++)
    {
 
        // decrement k if i is prime
        if (prime[i] == true)
            k--;
 
        // store the kth prime greater than n
        if (k == 0)
        {
            res = i;
            break;
        }
    }
    return res;
}
 
// Driver code
public static void main(String[] args)
{
    sieve();
    int n = 2, k = 15;
 
    // Print the kth prime number greater than n
    System.out.println(kthPrimeGreaterThanN(n, k));
}
}
 
// This code is contributed by 29AjayKumar

Python 3

# Python 3 program to print the Kth
# prime greater than N
 
# set the MAX_SIZE of the array to 10^6
MAX_SIZE = int(1e6)
 
# initialize the prime array
prime = [True] * (MAX_SIZE + 1)
 
# Code for Sieve of Eratosthenes
def sieve():
    p = 2
     
    while (p * p <= MAX_SIZE):
         
        # if prime[p] is not changed,
        # then it is a prime
        if (prime[p] == True):
             
            # update all multiples of p
            for i in range(p * p, MAX_SIZE, p):
                prime[i] = False
        p += 1
 
# Function to find the kth prime
# greater than n
def kthPrimeGreaterThanN(n, k):
    res = -1
     
    # looping through the numbers
    # greater than n
    for i in range(n + 1, MAX_SIZE):
         
        # decrement k if i is prime
        if (prime[i] == True):
            k -= 1
         
        # store the kth prime greater than n
        if (k == 0):
            res = i
            break
     
    return res
 
# Driver Code
if __name__=='__main__':
    n = 2
    k = 15
    sieve()
     
    # Print the kth prime number
    # greater than n
    print(kthPrimeGreaterThanN(n, k))
     
# This code is contributed by Rupesh Rao

C#

// C# program to print the
// Kth prime greater than N
using System;
using System.Collections.Generic;
     
class GFG
{
 
// set the MAX_SIZE of the array to 10^6
static int MAX_SIZE = (int) 1e6;
 
// initialize the prime array
static Boolean []prime = new Boolean[MAX_SIZE + 1];
 
static void sieve()
{
 
    // set all numbers as prime for time being
    for (int i = 0; i < MAX_SIZE + 1; i++)
        prime[i] = true;
 
    for (int p = 2; p * p <= MAX_SIZE; p++)
    {
 
        // if prime[p] is not changed,
        // then it is a prime
        if (prime[p] == true)
        {
 
            // update all multiples of p
            for (int i = p * p;
                     i <= MAX_SIZE; i += p)
                prime[i] = false;
        }
    }
}
 
// Function to find the kth prime greater than n
static int kthPrimeGreaterThanN(int n, int k)
{
 
    int res = -1;
     
    // looping through the numbers greater than n
    for (int i = n + 1; i < MAX_SIZE; i++)
    {
 
        // decrement k if i is prime
        if (prime[i] == true)
            k--;
 
        // store the kth prime greater than n
        if (k == 0)
        {
            res = i;
            break;
        }
    }
    return res;
}
 
// Driver code
public static void Main(String[] args)
{
    sieve();
    int n = 2, k = 15;
 
    // Print the kth prime number greater than n
    Console.WriteLine(kthPrimeGreaterThanN(n, k));
}
}
 
// This code is contributed by Rajput-Ji

Javascript

<script>
 
// Javascript program to print
// the Kth prime greater than N
 
// set the MAX_SIZE of the array to 10^6
var MAX_SIZE = 1000006;
 
// initialize the prime array
var prime = Array(MAX_SIZE + 1).fill(true);
 
function sieve()
{
 
 
    for (var p = 2; p * p <= MAX_SIZE; p++)
    {
 
        // if prime[p] is not changed,
        then it is a prime
        if (prime[p] == true) {
 
            // update all multiples of p
            for (var i = p * p; i <= MAX_SIZE; i += p)
                prime[i] = false;
        }
    }
}
// Function to find the kth prime greater than n
function kthPrimeGreaterThanN(n, k)
{
 
    var res = -1;
    // looping through the numbers greater than n
    for (var i = n + 1; i < MAX_SIZE; i++)
    {
 
        // decrement k if i is prime
        if (prime[i] == true)
            k--;
 
        // store the kth prime greater than n
        if (k == 0) {
            res = i;
            break;
        }
    }
 
    return res;
}
 
// Driver code
sieve();
var n = 2, k = 15;
// Print the kth prime number greater than n
document.write( kthPrimeGreaterThanN(n, k));
 
</script>
Producción: 

53

 

Publicación traducida automáticamente

Artículo escrito por rupesh_rao y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *