Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

235
Visualizações
How to find list of gcd of an array, while neglecting 0 to nth element(find gcd of (n-1) elements) one by one?

I was trying to solve a competitive programming question in java.
Original question: You will be given intensities Ai of N bugs. Now relative intensity of a bug can be calculated by taking the GCD of intensities of the rest of N-1 bugs. Given Q queries containing a single integer X you have to find the number of bugs having relative intensity greater than X. where

 1 <= N <= 10^5
 1 <= Q <= 10^5
 1 <= Ai <= 10^9
 1 <= X <= 10^5

I am getting TLE for 6 TCs out of 10. Can anyone help me for feasible solution?

My Code:

public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    int n=sc.nextInt();
    int t=sc.nextInt();
    int []arr=new int[n];
    for (int i = 0; i < n; i++) {
        arr[i]=sc.nextInt();
    }
    arr=mergeSort(arr);
    int gcd=arr[0];
    for(int i = 1; i < n; i++){
         gcd = gcd(gcd, arr[i]);
    }
    while(t-->0){
        int comp=sc.nextInt();
        int count=0;
        if (arr[1]>gcd) {
            int tempgcd=arr[1];
            for(int i = 2; i < n; i++){
                 tempgcd = gcd(tempgcd, arr[i]);
            }
            if (tempgcd>comp) {
                ++count;
            }
        }
        if (gcd>comp) {
            count=count+n-1;
        }
        System.out.println(count);
    }
    sc.close();

}
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Make two auxiliary arrays.
Fill L[] by gcd of elements from left to right.
Fill R[] by gcd of elements from right to left.
Now find relative intensity for i-th bug as gcd(L[i-1], R[i+1])

(optimizations are possible)

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda