You cannot improve brute force here, unfortunately, too much. The only thing you need to do is use the Eratosthenes sieve to pre-calculate all primes to a given number. After that, given the number N, recursively print all its sections, where the smallest prime is each prime from the list of primes in sequence (remember that it is the smallest so that you don't repeat the sections).
EDIT: Having learned that you need to know the number of sections: The 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 is the number that you calculate for the solution, and the second index is the minimum prime number that you should use for the section.
source share