Search code examples
pythonperformancemathcombinationsxor

How do display all possibilities to split up a number into multiple numbers


I have a for loop from range 0 to 1000 in which i want get all possible combinations of how the current number can be split up into for example 4 numbers and also use xor on these combinations :

split_up_in = 4
for i in range(0, 1000):
    combinations = getAllCombinationsXORs(i, split_up_in)
    print(combinations)

Update

Example:

i = 6

Split up into 4 numbers (only positive numbers without zero)

1 1 2 2 xor: 0 or 1 1 1 3 xor: 2 and so on filling in all the possibilities to sum up to the number i = 6

The order is not important. 1 1 2 2 is the same as 1 2 1 2


Is there any faster way to do it in python? Maybe an in-built function.


Solution

  • Partitioning a number n into k parts must have a complexity of O(n^(k-1)), since the number of partitions itself is proportional to that. Therefore there is no faster algorithm for this problem.

    If you want to print the results from 0 to 1000, then you should store the partitions and reuse them. Note that you only need to store the last k results because the recurrence relation has an order of k.