c - 搜索“count”个小于“bound”的不同奇数并加起来为“sum”
问题描述
我正在解决一个问题,该问题在 int 值 'bound' 下方找到 'count' 奇数,并将其加起来为 int 值总和。建议我用递归来解决。
我已经完成了递归,并在 mimir 中解决了 7 / 8 个案例。有一种情况显示失败,但即使使用 gdb 单步执行,我也无法弄清楚出了什么问题。问题案例:输入:10 54 108
编辑:所以事实证明我的代码是正确的并且正在为这种情况找到正确的答案(AKA - 不存在解决方案)但我的问题是我只有 3 秒的运行时间来找到这个解决方案,目前我的代码需要更长的时间比起那个来说。
不一定要寻找一个直接的答案,更多的是朝着正确的方向。试图从中学习:)
int odd_sum(int count, int bound, int sum)
{
if (bound % 2 == 0)
return odd_sum(count, bound -1, sum);
else if ( sum == 0 && count == 0 && bound >= -1)
return 1;
else if ( sum - bound < 0)
return odd_sum(count, bound - 2, sum);
else if (count == 0 && sum != 0)
return 0;
else if (bound < 1 && sum != 0)
return 0;
else
{
int value = (odd_sum(count - 1, bound - 2, sum - bound));
if ( value )
{
return printf("%d ", bound);
}
else
return (odd_sum(count - 1, bound - 2, sum - bound));
}
/* Do not change the main() function */
int main(void)
{
int value;
int c, b, s;
printf("Please enter 3 positive integers: count, bound, and sum:\n");
if (scanf("%d%d%d", &c, &b, &s) != 3) {
printf("Please enter 3 integers.\n");
return 1;
}
if (c <= 0 || b <= 0 || s <= 0) {
printf("Integers must be positive.\n");
return 1;
}
value = odd_sum(c, b, s);
if (value)
printf("\n");
else
printf("There are no solutions.\n");
return 0;
}
The final result needs to look like this for the two cases, ( pass or fail )
$./odd_sum
Please enter 3 positive integers: count, bound, and sum:
10 20 100
1 3 5 7 9 11 13 15 17 19
$./odd_sum
Please enter 3 positive integers: count, bound, and sum:
10 18 100
There are no solutions.
$./odd_sum
Please enter 3 positive integers: count, bound, and sum:
12 30 200
5 7 9 11 13 15 17 19 23 25 27 29
Thank you guys in advance
解决方案
此代码似乎返回正确的输入结果,(10、54、108):1 3 5 7 9 11 13 15 17 27
int odd_sum(int count, int bound, int sum){
if (count == 0 && sum == 0)
return 1;
if (count == 0 || bound <= 0)
return 0;
if (bound % 2 == 0)
return odd_sum(count, bound - 1, sum);
if (odd_sum(count - 1, bound - 2, sum - bound))
return printf("%d ", bound);
else
return odd_sum(count, bound - 2, sum);
return 0;
}
推荐阅读
- php - 按键计算数组值
- c - 虽然返回 si_addr 与 sigwaitinfo 函数的偏移量导致分段错误
- docker - 访问在端口 8080 上运行 REST API 的 docker 容器的 Travis CI 连接错误
- arrays - 在 PowerShell 中处理大型数组
- javascript - 如何将拖放的图像绘制到画布上
- c# - MQTTNet 监听主题消息
- linux - 让 gdb 自动读取 ./.gdbinit
- xamarin - 如何在 C# Xamarin Forms 中绑定到视图模型?
- python - 在 Intel Pentium 上安装 Tensorflow 和 Keras
- excel - 如何对多个条件使用 vlookup