A
A
artem782017-08-07 16:28:49
Python
artem78, 2017-08-07 16:28:49

Optimal algorithm for finding sum terms?

There are two similar tasks:

  1. Given an array of integers (can be equal to zero, negative and repeated). You need to find in it the first combination of two elements, which in total will give the number N.
    Example:
    N = 10
    [10, 5, 2, 3, 7, 5, -1]
         ^-----------^      5 + 5 = 10
               ^--^         3 + 7 = 10  <-- второй элемент встретился раньше,
                                            чем в предыдущем случае,
                                            поэтому берём эту пару

  2. Given an array of prime numbers from M to N inclusive. You need to find the first combination of two elements, the difference between which is equal to G.
    Example:
    G = 6
    M = 100  N = 110
    [101, 103, 107, 109]    <-- простые числа от M до N
      ^---------^           107 - 101 = 6  <-- пара появилась раньше
           ^---------^      109 - 103 = 6


In both tasks, you need to consider that:
  1. an array can have a huge number of elements (more than a million)
  2. suitable combinations of elements may not be in the array

I don't have any idea other than iterating over, comparing the sum/difference of all elements in this sequence:
1 и 2, 1 и 3, 1 и 4, ...
2 и 3, 2 и 4, 2 и 5, ...
и т.д.

But on a huge array, this method becomes indispensable. In addition, if there is no pair, I will only know about it after a full pass.
In the first task, the array consists of random values, but in the second, the sequence has a more or less uniform distribution and grows. I think this might help somehow.
What more optimal methods for finding terms can be applied to solve these problems?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
tsarevfs, 2017-08-07
@artem78

Let's reformulate the problem a bit: find the first number i such that there is j from 0 to i-1, such that a[i] + a[j] = N.

M
Matvey Pravosudov, 2017-08-07
@oxyberg

In the second example, even the algorithm is not needed, since the numbers are in a row:

$g = 6;
$m = 100;
$n = 110;
$array = [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110];

echo $array[0] . "-" . $array[$g - 1] . "=" . $g;

If you don't know if the numbers are increasing or decreasing, you can only compare the first two elements and choose the first combination based on that.
PS I just saw that there are prime numbers, although in the example the author has ordinary numbers.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question