algorithm - write a number as sum of a consecutive primes -
algorithm - write a number as sum of a consecutive primes -
how check if n
can partitioned sum of sequence of consecutive prime numbers.
for example, 12
equal 5+7
5 , 7 consecutive primes, 20
equal 3+17
3 , 17 not consecutive.
note that, repetition not allowed.
my thought find , list primes below n
, utilize 2 loops sum primes. first 2 numbers, sec 2 numbers, 3rd 2 numbers etc. , first 3 numbers, sec 3 numbers , far. takes lot of time , memory.
realize consecutive list of primes defined 2 pieces of information, starting , ending prime number. have find these 2 numbers.
i assume have primes @ disposal, sorted in array called primes
. maintain 3 variables in memory: sum
2 (the smallest prime), first_index
, last_index
0 (index of smallest prime in array primes
).
now have "tweak" these 2 indices, , "travel" array along way in loop:
if sum == n
finish. have found sequence of primes.
if sum < n
enlarge list adding next available prime. increment last_index
one, , increment sum
value of new prime, primes[last_index]
. repeat loop. if primes[last_index]
larger n
there no solution, , must finish.
if sum > n
cut down list removing smallest prime list. decrement sum
value, primes[first_index]
, , increment first_index
one. repeat loop.
algorithm primes
Comments
Post a Comment