Cuente números enteros en el rango [L, R] no divisible por los primeros números primos K

Dados dos números enteros positivos L y R , la tarea es encontrar el número de números en el rango [L, R] que no son divisibles por ninguno de los primeros K números primos. 

Entrada: L = 10, R = 25, K = 3
Salida: 5
Explicación: En el rango dado hay 5 números 11, 13, 17, 19, 23 que no son divisibles por ninguno de los primeros 3 números primos. 
Entonces la cuenta es 5.

Entrada : L = 50, R = 1000, K = 5
Salida: 196

 

Enfoque: El problema dado se puede resolver usando la siguiente idea: 

Primero almacene los primeros K números primos y luego recorra todos los números en el rango [L, R] y verifique si son divisibles por alguno de los primeros K números primos o no

  • Almacena los K números primos en un vector usando la Tamiz de Eratóstenes .
  • Luego, para todos los K números primos, itere un bucle y marque todos los múltiplos de ese número primo en L a R como divisibles por cualquiera de los primeros K números primos.
  • Después de esto, itera un ciclo y cuenta los números que están marcados como no divisibles en L a R.
  • El conteo final es la respuesta requerida.

A continuación se muestra la implementación del enfoque anterior.

C++

// C++ code to implement above approach
#include <bits/stdc++.h>
using namespace std;
 
// Code for Sieve of Eratosthenes
// to store first k prime numbers
void SieveOfEratosthenes(int n,
                         vector<int>& v, int k)
{
    bool prime[n + 1];
    memset(prime, true, sizeof(prime));
 
    for (int i = 2; i * i <= n; i++) {
        if (prime[i]) {
            for (int j = i * i; j <= n;
                 j += i)
                prime[j] = false;
        }
    }
 
    // Storing first k prime numbers
    // in vector v.
    for (int i = 2; i < n; i++) {
        if (prime[i]) {
            v.push_back(i);
        }
        if (v.size() == k) {
            break;
        }
    }
}
 
// Function to return the count
// of numbers in range L and R
// which is not divisible by first
// k prime numbers
int total_count(int L, int R, int k)
{
    vector<int> v;
 
    // Calling sieve of eratosthenes
    SieveOfEratosthenes(100000, v, k);
 
    // Initialising the array
    int arr[R + 1] = { 0 };
 
    // Making all the multiples of
    // every prime number in the
    // array arr as 1.
    for (int i = 0; i < v.size(); i++) {
 
        // Val is the first multiple
        // of v[i] which is greater
        // or equal to L.
        int val;
 
        if (L % v[i] == 0) {
            val = L;
        }
        else {
            val = ((L / v[i]) + 1) * v[i];
        }
        for (int j = val; j <= R; j = j
                                      + v[i]) {
            arr[j] = 1;
        }
    }
 
    int count = 0;
    for (int i = L; i <= R; i++) {
        if (arr[i] == 0) {
            count++;
        }
    }
 
    return count;
}
 
// Driver code
int main()
{
    int L = 10, R = 25;
    int K = 3;
 
    // Function call
    cout << total_count(L, R, K);
    return 0;
}

Java

// Java code to implement above approach
import java.io.*;
import java.util.Vector;
 
class GFG {
 
  // Code for Sieve of Eratosthenes
  // to store first k prime numbers
  static void SieveOfEratosthenes(int n,
                                  Vector<Integer> v, int k)
  {
    boolean[] prime = new boolean[n + 1];
    for(int i = 0; i < n + 1; i++) prime[i] = true;
 
    for (int i = 2; i * i <= n; i++) {
      if (prime[i]) {
        for (int j = i * i; j <= n;
             j += i)
          prime[j] = false;
      }
    }
 
    // Storing first k prime numbers
    // in vector v.
    for (int i = 2; i < n; i++) {
      if (prime[i]) {
        v.add(i);
      }
      if (v.size() == k) {
        break;
      }
    }
  }
 
  // Function to return the count
  // of numbers in range L and R
  // which is not divisible by first
  // k prime numbers
  static int total_count(int L, int R, int k)
  {
    Vector<Integer> v = new Vector<>();
 
    // Calling sieve of eratosthenes
    SieveOfEratosthenes(100000, v, k);
 
    // Initialising the array
    int[] arr = new int[R + 1];
 
    // Making all the multiples of
    // every prime number in the
    // array arr as 1.
    for (int i = 0; i < v.size(); i++) {
 
      // Val is the first multiple
      // of v[i] which is greater
      // or equal to L.
      int val;
 
      if (L % v.get(i) == 0) {
        val = L;
      }
      else {
        val = ((L / v.get(i)) + 1) * v.get(i);
      }
      for (int j = val; j <= R; j = j
           + v.get(i)) {
        arr[j] = 1;
      }
    }
 
    int count = 0;
    for (int i = L; i <= R; i++) {
      if (arr[i] == 0) {
        count++;
      }
    }
 
    return count;
  }
 
  // Driver code
  public static void main (String[] args) {
    int L = 10, R = 25;
    int K = 3;
 
    // Function call
    System.out.print(total_count(L, R, K));
  }
}
 
// This code is contributed by hrithikgarg03188.

Python3

# python3 code to implement above approach
import math
 
# Code for Sieve of Eratosthenes
# to store first k prime numbers
def SieveOfEratosthenes(n, v, k):
 
    prime = [True for _ in range(n + 1)]
 
    for i in range(2, int(math.sqrt(n)) + 1):
        if (prime[i]):
            for j in range(i*i, n + 1, i):
                prime[j] = False
 
    # Storing first k prime numbers
    # in vector v.
    for i in range(2, n):
        if (prime[i]):
            v.append(i)
 
        if (len(v) == k):
            break
 
# Function to return the count
# of numbers in range L and R
# which is not divisible by first
# k prime numbers
def total_count(L, R, k):
 
    v = []
 
    # Calling sieve of eratosthenes
    SieveOfEratosthenes(100000, v, k)
 
    # Initialising the array
    arr = [0 for _ in range(R + 1)]
 
    # Making all the multiples of
    # every prime number in the
    # array arr as 1.
    for i in range(0, len(v)):
 
        # Val is the first multiple
        # of v[i] which is greater
        # or equal to L.
        val = 0
 
        if (L % v[i] == 0):
            val = L
 
        else:
            val = ((L // v[i]) + 1) * v[i]
 
        for j in range(val, R + 1, v[i]):
            arr[j] = 1
 
    count = 0
    for i in range(L, R+1):
        if (arr[i] == 0):
            count += 1
 
    return count
 
# Driver code
if __name__ == "__main__":
 
    L, R = 10, 25
    K = 3
 
    # Function call
    print(total_count(L, R, K))
 
    # This code is contributed by rakeshsahni

C#

// C# code to implement above approach
using System;
using System.Collections.Generic;
class GFG {
 
  // Code for Sieve of Eratosthenes
  // to store first k prime numbers
  static void SieveOfEratosthenes(int n, List<int> v,
                                  int k)
  {
    bool[] prime = new bool[n + 1];
    for (int i = 0; i < n + 1; i++)
      prime[i] = true;
 
    for (int i = 2; i * i <= n; i++) {
      if (prime[i]) {
        for (int j = i * i; j <= n; j += i)
          prime[j] = false;
      }
    }
 
    // Storing first k prime numbers
    // in vector v.
    for (int i = 2; i < n; i++) {
      if (prime[i]) {
        v.Add(i);
      }
      if (v.Count == k) {
        break;
      }
    }
  }
 
  // Function to return the count
  // of numbers in range L and R
  // which is not divisible by first
  // k prime numbers
  static int total_count(int L, int R, int k)
  {
    List<int> v = new List<int>();
 
    // Calling sieve of eratosthenes
    SieveOfEratosthenes(100000, v, k);
 
    // Initialising the array
    int[] arr = new int[R + 1];
 
    // Making all the multiples of
    // every prime number in the
    // array arr as 1.
    for (int i = 0; i < v.Count; i++) {
 
      // Val is the first multiple
      // of v[i] which is greater
      // or equal to L.
      int val;
 
      if (L % v[i] == 0) {
        val = L;
      }
      else {
        val = ((L / v[i]) + 1) * v[i];
      }
      for (int j = val; j <= R; j = j + v[i]) {
        arr[j] = 1;
      }
    }
 
    int count = 0;
    for (int i = L; i <= R; i++) {
      if (arr[i] == 0) {
        count++;
      }
    }
 
    return count;
  }
 
  // Driver code
  public static void Main(string[] args)
  {
    int L = 10, R = 25;
    int K = 3;
 
    Console.Write(total_count(L, R, K));
  }
}
 
// This code is contributed by ukasp.

Javascript

<script>
// JavaScript code for the above approach
 
// Code for Sieve of Eratosthenes
// to store first k prime numbers
function SieveOfEratosthenes(n,
                       v,  k)
{
    let prime= new Array(n+1).fill(true);
     
 
    for (let i = 2; i * i <= n; i++) {
        if (prime[i]) {
            for (let j = i * i; j <= n;
                 j += i)
                prime[j] = false;
        }
    }
 
    // Storing first k prime numbers
    // in vector v.
    for (let i = 2; i < n; i++) {
        if (prime[i]) {
            v.push(i);
        }
        if (v.length == k) {
            break;
        }
    }
}
 
// Function to return the count
// of numbers in range L and R
// which is not divisible by first
// k prime numbers
function total_count( L,  R,  k)
{
    let v =[];
 
    // Calling sieve of eratosthenes
    SieveOfEratosthenes(100000, v, k);
 
    // Initialising the array
    let arr = new Array(R+1).fill(0);
 
    // Making all the multiples of
    // every prime number in the
    // array arr as 1.
    for (let i = 0; i < v.length; i++) {
 
        // Val is the first multiple
        // of v[i] which is greater
        // or equal to L.
        let val;
 
        if (L % v[i] == 0) {
            val = L;
        }
        else {
            val = (Math.floor(L / v[i]) + 1) * v[i];
        }
        for (let j = val; j <= R; j = j
                                      + v[i]) {
            arr[j] = 1;
        }
    }
 
    let count = 0;
    for (let i = L; i <= R; i++) {
        if (arr[i] == 0) {
            count++;
        }
    }
 
    return count;
}
 
// Driver code
    let L = 10, R = 25;
    let K = 3;
 
    // Function call
    document.write(total_count(L, R, K));
   
   // This code is contributed by Potta Lokesh
 
    </script>
Producción

5

Complejidad de tiempo: O(N*log(log(N)) + K*R) donde N es un valor positivo alto
Espacio auxiliar: O(N+R)

Publicación traducida automáticamente

Artículo escrito por pushpeshrajdx01 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 *