Number of distinct prime partitions [duplicate]

时光总嘲笑我的痴心妄想 提交于 2019-12-04 09:12:56

To solve this one you are going to need to combine three ideas:

Say the given number is n:

  • find all primes less than n, as shown here.

  • dynamically calculate the subset sum from your prime array and n. A few hints are here and here

  • then, calculate the number of distinct permutations of each answer you get from step two, as here.

Now of course, this is just a hint. But it should help you a great deal to cook up your final code.

So, in the form of hints as opposed to an answer:

  • As has been said elsewhere, you can precompute the primes.
  • Can you reuse results from a smaller number? So, assuming you know the actual permutations for 5, does this help you find any of the actual permutations for 7?
  • Is there any structure to the results, and if so, can you use that structure to avoid repeating calculations? For example, you list 5 permutations for number 7, but these exhibit some similarity to each other - is that a general trend, and what is it?
  • Assuming you find internal structure and can use smaller results to help find larger ones, can you do both - can you entirely avoid storing the complete intermediate results?
  • Finally, do you need to list each ordered combination or just return the number of ordered combinations? You may be able to save computation here.

You can not improve the brute force here too much unfortunately. One thing you should definitely do is to use an sieve of Eratosthenes to precalculate all the prime numbers up to a given number. After that given a number N recursively print all its partitions where the smallest prime number is each prime from the list of prime numbers consecutively(remember to have it being the smallest one so that you don't repeat partitions).

EDIT: after knowing you only need to know the count of partitions: best solution would be to use dynamic programming. Again you will need to memoize in an array with two dimensions mem[MAX_SIZE][MAX_SIZE] first index being the number you are computing the solution for and the second index being the index of the minimum prime number you should use for the partition.

user570500

You may want to look at the mathematics of partitions at Wikipedia in particular the sections on the Generating Function and on Restricted Partition Generating Functions about half-way down the page. It mentions a generating function for partitions consisting of particular summands (specified by a set T of natural numbers).

Let the number of non-order-dependent prime-partitions of the number n be R(n). You can derive R(n) from the generating function by taking the n-th partial derivative w.r.t x and setting then x = 0. This may not be easy.

One caveat: these partitions are not order dependent (i.e. 1 + 2 and 2 + 1 are counted only as one partition).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!