首页 > 解决方案 > 如何制作一个代码,为数字 x 生成所有整数分区,其中 y 作为 C# 分区中可用的最大数字

问题描述

例如,输入“5 3”给出 5 作为分区数(3+2、3+1+1、2+2+1、2+1+1+1、1+1+1+1+1) ,不包括 5 或 4+1,因为它们包含大于 y 的整数。

我还没有发现参数 x 和 y 与输出之间有任何相关性。这是我迄今为止设法制作的代码。它检测包含 1 和单个其他数字的潜在组合。到目前为止,我还没有找到一种方法来让它检测多个大于 1 的数字。

class Program
    {
        static void Main(string[] args)
        {
            string input = Console.ReadLine();
            string[] inputs = input.Split();
            int max = Convert.ToInt32(inputs[0]);
            int amount = Convert.ToInt32(inputs[1]);
            int path = max;
            int how_many = 1; // said one is 1+1+1...
            int x = 2;
            while (x <= amount)
            {
                while (path >= x) //only 1 and another number
                {
                    path -= x;
                    how_many += 1;
                }
                path = max;
                x += 1;
            }
            Console.WriteLine(how_many);
            Console.ReadKey();
        }

标签: c#combinatorics

解决方案


抱歉,不是 C#,而是 python3 解决方案(递归),适用于 C#,只是我不是 Windows 粉丝:

def solution(n, m):
    if n < 2 or m < 2:
        return 1
    if n < m:
        return solution(n, n)  ## or m = n
    return solution(n-m, m) + solution(n, m-1)

print(solution(5, 3))
#5
print(solution(8,4))
#15
#4+4, 4+3+1, 4+2+2, 4+2+1+1, 4+1+1+1+1
#3+3+2 3+3+1+1 3+2+2+1 3+2+1+1+1 3+1+1+1+1+1
#2+2+2+2  2+2+2+1+1 2+2+1+1+1+1 2+1+1+1+1+1+1 1+1+1+1+1+1+1+1+1

如果对于大N和M来说太慢了,就用数组或列表来存储早期的结果,那只是“技术”。


推荐阅读