Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest algorithm to determine if any number in a sorted array is multiple of `x`?

Tags:

algorithm

math

Given an positive integer x and a sorted positive integer array A

Is there any algorithm faster than O(N) to determine if any element in A is a multiple of x? There are no negative elements in A.

Naive looping A once is my only idea so far, I do not know if there is any way to make use of the fact that A is sorted to speed it up.

like image 930
shole Avatar asked Jul 21 '17 08:07

shole


People also ask

What is the fastest we can find whether a given integer is present in a sorted array of integers?

Since all sorting algorithms are bound below by Ω(n), I would argue that both radix sort and bucket sort are the fastest algorithms for sorting an array of integers.

Which sorting algorithm will be fastest when run on an array that happens to already be in order?

Show activity on this post. Is normally always the fastest and easiest to implement when an array is already nearly or completely sorted. As we have less operations. Selection sort will still do pair wise comparison and binary sort will also be slightly slower.

Which algorithm can be used to find an element in a sorted array?

In computer science, binary search, also known as half-interval search, logarithmic search, or binary chop, is a search algorithm that finds the position of a target value within a sorted array. Binary search compares the target value to the middle element of the array.

What is the time complexity of finding a number in a sorted array?

Elements in a sorted array can be looked up by their index (random access) at O(1) time, an operation taking O(log n) or O(n) time for more complex data structures.


1 Answers

This seems to depend very much on the size of x and the number of elements within A, and particularly the number of candidate multiples of x within A.

Binary-searching a specific number within A takes O(log(n)) time (n being the number of elements within A), so if there are k possible multiples of x between the first and the last element of A, it will take O(k * log(N)) to check them all. If that number is smaller than n, you can use this algorithm, otherwise just do a linear search.

(Also, there are probably a few small optimizations to above algorithm. E.g., once you checked x*i (and did not find it), you can use the position where x*i should have been as the lower bound when searching for x*(i+1) instead of the very first element of the array.)

like image 177
tobias_k Avatar answered Sep 18 '22 15:09

tobias_k