Compound minimum search

If you are given prime numbers: 2, 3, 5, 7,
there is an effective way to find out the minimum compound number greater than some given number, which has no simple factor other than the allowed primes.

For example:
Given a lot of primes: 2, 3, 5, 7 If we want to find a compound number that must be greater than or equal 85to and has no prime coefficient other than 2, 3, 5, or 7, the answer should be 90.
because

85 = 5 * 17 (wrong)  
86 = 2 * 43 (wrong)  
87 = 3 * 29 (wrong)  
88 = (2 ^ 3) * 11 (wrong)  
89 = 89 (wrong)  
90 = 2 * (3 ^ 2) * 5 (correct)
+4
source share
3 answers

You find the smallest number 2 ^ i 3 ^ j 5 ^ k 7 ^ l, which is greater than or equal to some N.

, , N.

1, (i, j, k, l) = (0,0,0,0). - H S (, -).

, , N:

  • (i, j, k, l) H
  • (i + 1, j, k, l), (i, j + 1, k, l), (i, j, k + 1, l) (i, j, k, l +1) H S, S.

, , , / , .

python:

import heapq
N = 85
S = set([(0,0,0,0)])
H = [( 1 , (0,0,0,0) )]
while True:
    val,(i,j,k,l) = heapq.heappop(H)
    if val >= N:
        break
    if (i+1,j,k,l) not in S:
        S.add((i+1,j,k,l))
        heapq.heappush(H,( val*2 , (i+1,j,k,l) ) )
    if (i,j+1,k,l) not in S:
        S.add((i,j+1,k,l))
        heapq.heappush(H,( val*3 , (i,j+1,k,l) ) )
    if (i,j,k+1,l) not in S:
        S.add((i,j,k+1,l))
        heapq.heappush(H,( val*5 , (i,j,k+1,l) ) )
    if (i,j,k,l+1) not in S:
        S.add((i,j,k,l+1))
        heapq.heappush(H,( val*7 , (i,j,k,l+1) ) )

print val # 90

, O (log N) . 3 H S, O (3 log N). , / O (log log N), O (log N * log log N).

0
  • .

  • .

  • , , .

  • .

  • 2.

+1

, , : 85 . . , n 1 .

: :

2^a2 * 3^a3 * 5^a5 * 7^a7

{a2, a3, a5, a7}. {0, 0, 0, 0}, 1, 0. , , , , .

, , .

:

function spread(p[], ix, num, lim)
{
    if (num >= lim) {
        return min;
    } else {
        m1 = spread(p, ix, k * p[ix], lim, min);

        ix++;
        if (ix == p.length) return m1

        m2 = spread(p, n, ix, num, lim, min);
        return min(m1, m2);
    }
}

min = spread([2, 3, 5, 7], 0, 1, 85)

This approach will not buy you much in your example, but should be better for large primes and cases where the minimum is not close to the threshold.

+1
source

Source: https://habr.com/ru/post/1531989/


All Articles