Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

230
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!