c - 搜索 `count'个小于 `bound'的不同奇数加起来为 `sum'

标签 c recursion

我正在解决一个问题,该问题找到低于 int 值“绑定(bind)”的“计数”个奇数,并将其加起来为一个 int 值总和。建议我用递归来解决。

我已经完成了递归并在 mimir 中解决了 7/8 个案例。有一种情况显示失败,但即使使用 gdb 单步执行,我也无法弄清楚出了什么问题。 问题案例: 输入:10 54 108

编辑: 所以事实证明我的代码是正确的并且正在为这种情况找到正确的答案(AKA - 不存在解决方案)但我的问题是我只有 3 秒的运行时间来找到这个解决方案,目前我的代码需要比这更长的时间.

不一定要寻找直接的答案,更多的是指向正确的方向。尝试从中学习:)

https://ibb.co/4138WBw

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;
}

关于c - 搜索 `count'个小于 `bound'的不同奇数加起来为 `sum',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58054647/

相关文章:

c - fgets();这部分代码是如何工作的? C语言编程

c - 数组地址是随机的还是固定的?

java - 在 Java 中重复排列数组

haskell - Church-encoded 列表的 Catamorphisms

java - 在 Java 中处理递归阶乘函数中的负整数

c - 程序退出状态

c - 在不同级别使用不同的枚举类型

C:字符串,段错误

java - 为什么这个递归方法超出了我的预期

node.js - 解析域时如何处理 CNAME?