There is a simple O (n.sqrt (n)) algorithm:
Initialize an array D to all -1. For i = 1,2,...,n Let a = A[i] Output D[a] For each divisor d of A[i]: set D[d] = i
You can find all the divisors of a number in O (sqrt (n)) with a simple loop, or you can quickly find some preliminary factorization calculation.
The algorithm works with D [x] to save the position j of the last number A [j], a multiple of x.
source share