vba - How can I find the first four consecutive numbers with four free denominators? -
the first 2 consecutive numbers 2 free denominators are:
14 = 2 × 7 15 = 3 × 5
the first 3 consecutive numbers 3 free denominators are:
644 = 2 × 7 × 23 645 = 3 × 5 × 43 646 = 2 × 17 × 19
how can find first 4 consecutive numbers 4 free denominators?
it isn't case 644 = 2 x 7 x 23. rather 644 = 2 x 2 x 7 x 23 -- looking numbers have distinct prime divisors which might repeated. in fact, 1309, 1310, 1311 first 3 numbers have 3 distinct non-repeated factors, , impossible 4 since run of 4 successive numbers have repeated factor of 4.
to solve problem of finding 4 successive numbers each of has 4 distinct (albeit possibly repeated) prime factors, can use modified version of sieve of eratosthenes, 1 keeps track of number of distinct divisors:
function sievek(n long, k long) long 'implements modified sieve of erasthones 'to return first of k successive numbers 'less or equal n, each of has 'k distinct prime factors. 'returns -1 if no such number exists dim nums variant dim long, p long dim run long dim limit long dim primes variant primes = array(2, 3, 5, 7, 11, 13) 'small primes p = 1 = 0 k - 2 p = p * primes(i) next limit = int(1 + n / p) redim nums(2 n) long p = 2 'first prime while p < limit 'mark subsequent multiples of p adding 1 = 2 * p n step p nums(i) = nums(i) + 1 next 'find next p -- next 0 p = p + 1 while nums(p) <> 0 p = p + 1 loop loop 'at stage, numbers marked. 'primes marked 0 , composites marked 'by number of distinct prime factors. 'check run of k ks run = 0 = 2 n if nums(i) = k run = run + 1 if run = k 'we have winner! sievek = - k + 1 exit function end if else 'reset run counter run = 0 end if next sievek = -1 end function
sievek(10^6,4)
evaluates 134043 in less second. function doesn't yield factorization of or next 3 numbers, easy find. sievek(10^8,5)
evaluates -1, there isn't run less 100 million of 5 consecutive numbers each of has 5 different prime factors.
remark: in earlier version of answer had logic flaw (which didn't prevent output being correct). namely -- had sieved square root of n, though if e.g. number m looks 2x3x5xp p prime m have 4 distinct prime factors though p might exceed square root of n. revised algorithm take care of possibility.
Comments
Post a Comment