交替递增序列

时间:2012-06-25 15:01:46

标签: c recursion sequence

上午 -

我需要一个可以产生以下类型的序列的函数:

1, -1, 2, -2, 3...

尾递归函数是否是处理此问题的最佳方法?有没有办法迭代地执行此操作而不是递归?

5 个答案:

答案 0 :(得分:10)

这个序列有一个简单的非递归形式:

A[n] = (n + 1) / 2 - (n % 2 ? 0 : n)

取决于索引。

答案 1 :(得分:3)

return (n>>1) * -(n&1);

答案 2 :(得分:1)

可能的方法是使用abs()函数:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i = 0;
    while (i-- > -10) printf(" %d %d", i, abs(i));
    printf("\n");
    return 0;
}

答案 3 :(得分:1)

如果我正确理解了这个问题,那么像下面这样的简单函数可以提供帮助。如果你想对它做更多的事情,你需要编写更多的代码。

void calc_sequence(int *arr, int size)
{
   int i=0;
   int j=0;


    for(i=1; i<=(size/2); i++)
    {
      arr[j] = i;
      arr[j+1] = -i;
      j = j+2;
    }
 }


 /* The below code should come in the calling function. n is the maximum positive number you plan to see in the sequence */

   int *arr = malloc((n*2) * sizeof(int));
   calc_sequence(arr, (n*2));

答案 4 :(得分:1)

您可以迭代地使用构建序列。

int *
f(size_t size)
{
    int *p = malloc(size * sizeof *p); // Checks for overflows

    for (size_t i = 0; i < size; ++i) {
        p[i] = (i + 1) / 2;
        if (i & 1) p[i] -= i;
    }

    return p;
}