How to find a maximal odd decomposition of integer M?

前端 未结 3 1275
遥遥无期
遥遥无期 2021-02-09 18:40

Let M be an integer in range [1; 1,000,000,000].

A decomposition of M is a set of unique integers whose sum is equal to M.

A decomposition is odd

3条回答
  •  无人共我
    2021-02-09 19:39

    Here is a deterministic solution to the problem. Suppose M = {1, 3, 5, ..., 2*k-3, 2*k-1, r} where r <= 2*k + 1. It is 'obvious' that the maximal decomposition is not going to have more numbers than (k+1).

    We have the following cases for k > 3 (the reasoning and handling of earlier cases is presented later):

    Case 1. If r is odd and equal to 2*k+1: add r into the list thereby giving a decomposition of (k+1) elements.

    Case 2. If r is even: replace {(2*k-1), r} by {2*k-1+r} giving a decomposition of k elements.

    Case 3. If r is odd and not equal to 2*k+1: replace the first and the last two elements in the series {1, 2*k-1, r} by {2*k+r} giving a decomposition of (k-1) elements.

    Note that the worst case of (k-1) elements will occur when the input is of the form n^2 + (odd number < 2*k+1).

    Also note that (Case 3) will break in case the number of elements is less than 3. For example, the decomposition of 5 and 7. We will have to special-case these numbers. Likewise (Case 2) will break for 3 and will have to be special-cased. There is no solution for M=2. Hence the restriction k > 3 above. Everything else should work fine.

    This takes O(sqrt(M)) steps.

    Some C/C++ code:

    #include 
    
    int main(int argc, char *argv[])
    {
        printf("Enter M:");
        int m = 0;
        scanf("%d", &m);
    
        int arr[100] = {0};
        printf("The array is:\n");
        switch(m) {
            case 2:
                printf("No solution\n");
                return 0;
            case 1:
            case 3:
            case 5:
            case 7:
                printf("%d\n", m);
                return 0;
        }
    
        int sum = 0;
        int count = 0;
        for (int i = 1; (sum + i) < m; i+= 2) {
            arr[count++] = i;
            sum += i;
        }
        int start = 0;
        int r = m - sum;
        if (r % 2 == 0) {
            arr[count - 1] += r;
        } else if (r > arr[count - 1]) {
            arr[count++] = r;
        } else {
            start = 1;
            arr[count - 1] += r + 1;
        }
    
        for (int i = start; i < count; i++) {
            printf("%d\n", arr[i]);
        }
    
        return 0;
    }
    

    Example:

    Enter M:24
    The array is:
    1
    3
    5
    15
    
    Enter M:23
    The array is:
    3
    5
    15
    

提交回复
热议问题