【发布时间】:2015-12-22 21:42:34
【问题描述】:
所以我有一个整数,例如1234567890,以及一组给定的数字,例如{4、7、18、32、57、68}
问题是 1234567890 是否可以由给定的数字组成(您可以多次使用一个数字,而不必使用所有这些数字)。在上述情况下,一种解决方案是:
38580246 * 32 + 1 * 18
(不需要给出具体的解决方案,只要能做到就行)
我的想法是尝试所有解决方案。例如我会尝试
1 * 4 * + 0 * 7 + 0 * 18 + 0 * 32 + 0 * 57 + 0 * 68 = 4
2 * 4 * + 0 * 7 + 0 * 18 + 0 * 32 + 0 * 57 + 0 * 68 = 8
3 * 4 * + 0 * 7 + 0 * 18 + 0 * 32 + 0 * 57 + 0 * 68 = 12
.....
308 641 972 * 4 * + 0 * 7 + 0 * 18 + 0 * 32 + 0 * 57 + 0 * 68 = 1234567888
308 641 973 * 4 * + 0 * 7 + 0 * 18 + 0 * 32 + 0 * 57 + 0 * 68 = 1234567892 ==> 超过
0 * 4 * + 1 * 7 + 0 * 18 + 0 * 32 + 0 * 57 + 0 * 68 = 7
1 * 4 * + 1 * 7 + 0 * 18 + 0 * 32 + 0 * 57 + 0 * 68 = 11
2 * 4 * + 1 * 7 + 0 * 18 + 0 * 32 + 0 * 57 + 0 * 68 = 15
等等...
这是我在 c# 中的代码:
static int toCreate = 1234567890;
static int[] numbers = new int[6] { 4, 7, 18, 32, 57, 68};
static int[] multiplier;
static bool createable = false;
static void Main(string[] args)
{
multiplier = new int[numbers.Length];
for (int i = 0; i < multiplier.Length; i++)
multiplier[i] = 0;
if (Solve())
{
Console.WriteLine(1);
}
else
{
Console.WriteLine(0);
}
}
static bool Solve()
{
int lastIndex = 0;
while (true)
{
int comp = compare(multiplier);
if (comp == 0)
{
return true;
}
else if (comp < 0)
{
lastIndex = 0;
multiplier[multiplier.Length - 1]++;
}
else
{
lastIndex++;
for (int i = 0; i < lastIndex; i++)
{
multiplier[multiplier.Length - 1 - i] = 0;
}
if (lastIndex >= multiplier.Length)
{
return false;
}
multiplier[multiplier.Length - 1 - lastIndex]++;
}
}
}
static int compare(int[] multi)
{
int osszeg = 0;
for (int i = 0; i < multi.Length; i++)
{
osszeg += multi[i] * numbers[i];
}
if (osszeg == toCreate)
{
return 0;
}
else if (osszeg < toCreate)
{
return -1;
}
else
{
return 1;
}
}
代码运行良好(据我所知),但速度太慢了。求解这个例子大约需要 3 秒,100 个数字可能有 10000 个数字。
【问题讨论】:
-
假设集合中的数字互质,我是否正确?
-
在我看来,您可以通过预先为每个数字做一些基本的数学运算来消除很多潜在的答案。例如,您知道,当您只添加一个数字时,您只需检查所需的数字是否可以被该数字整除。这是一次检查,而不是遍历每个可能的数字,直到超过所需的数字
-
模数运算符可能是你的朋友。您可以从
1234567890 % 68开始,然后看看您是否可以从其他较小的数字中创建余数。这会先把它变成一个小问题。 -
@TrentSartain 这是我想说的一个更清楚的例子
-
如果代码运行良好,上 CodeReview 不是更好吗?
标签: c# math numbers number-theory