Finding $GCD$ excluding some elements from an $array$

820 Views Asked by At

I have an array of numbers. I want to calculate $GCD$ of all numbers but excluding numbers from particular index $a$ to index $b$.

I need to repeat the same operation multiple times with different values of $a$ and $b$.
Is there any better way other than the obvious $Brute Force$ one?

1

There are 1 best solutions below

1
On BEST ANSWER

Note that the GCD of (integer?) array elements c[1..n] excluding c[a..b] is the GCD of the two values, GCD of c[1..(a-1)] and GCD of c[(b+1)..n].

So if you formed the (descending) sequence of GCD's of the initial segments c[1..k] and those of the terminal segments c[m..n], you would be able to find all the queries of GCD's excluding some intervening segment c[a..b] in constant time (taking the GCD of two previously computed results).