How to find a maximal odd decomposition of integer M?

前端 未结 3 1274
遥遥无期
遥遥无期 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:17

    Here is an idea which should work. It requires a net removal of at most 1 number from the greedy set you construct.

    Construct your O(sqrt(M)) list as usual (without result[len - 1] = M - sum;). If the sum is not a square number (i.e. exact):

    • Add the next largest odd number
    • Take the difference between your sum now and your target number -> N

      • If N is odd, remove the corresponding number
      • If N is even but not 2, remove the largest odd number smaller than N, and the 1
      • If N is 2, remove the penultimate number you just added. This will make the difference 0

    Proof:

    • If you add the consecutive odd numbers sequentially then the list should be as dense as possible - i.e. you cannot have a larger list
    • Also the difference is always bounded by the odd number you add in step 2, so a net removal of up to two numbers is always accounts of either odd or even differences.

    Examples:

    • Say you want 42: construct [1, 3, 5, 7, 9, 11], add 13 => sum = 49, remove 7 (no net removal)
    • You want 39: construct [1, 3, 5, 7, 9, 11], add 13, remove 1 and 9 (net removal of 1)
    • You want 38: construct [1, 3, 5, 7, 9, 11], add 13, remove 11 (no net removals)

    EDIT: error in last case corrected courtesy of @user1952500

提交回复
热议问题