这是生成斐波那契数列的更好方法

发布于 2024-11-07 08:16:13 字数 554 浏览 3 评论 0原文

斐波那契数列生成的两种通用方法是:

  1. 传统方法,即在函数内运行 for 循环。
  2. 递归

我遇到了另一个解决方案

#include <iostream>

using namespace std;

void fibo() {
 static int y = 0;
 static int x = 1;
 cout << y << endl;
 y = x + y;
 x = y - x;
}

int main() {
 for (int i = 1; i <= 1; i++) {
  fibo();
 }
 return 0;
}

该解决方案在初始运行中看起来运行良好,但是与传统方法和递归方法相比,这是否有任何显着的缺点?

我确信静态变量会增加空间复杂度,但至少我们没有使用递归构建函数表堆栈,对吗?

The two general approaches for Fibonacci series generation are:

  1. The traditional approach, i.e., running through a for loop inside a function.
  2. Recursion

I came across another solution

#include <iostream>

using namespace std;

void fibo() {
 static int y = 0;
 static int x = 1;
 cout << y << endl;
 y = x + y;
 x = y - x;
}

int main() {
 for (int i = 1; i <= 1; i++) {
  fibo();
 }
 return 0;
}

This solution looks to be working fine in the initial runs, but when compared to the traditional and recursion approach, does this hold any significant disadvantages?

I am sure static variables would add to space complexity, but at least we are not building a function table stack using recursion, correct?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

2024-11-14 08:16:13

我可以立即看到缺点:

  • 本质上使状态成为全局的,它不是线程安全的
  • 你只能运行一次序列,因为没有办法重置

我会赞成一种将状态保留在你可以询问的对象内的方法基本上,对于 - 迭代器的下一个值。 (我一直不确定斐波那契数列映射到 C++ 迭代器有多容易;但它在 C# 和 Java IEnumerableIterable 上工作得很好。)

Disadvantages I can immediately see:

  • By essentially making the state global, it's not thread-safe
  • You can only ever run through the sequence once, as there's no way to reset

I would favour an approach which keeps the state within an object which you can ask for the next value of - an iterator, basically. (I've never been certain how easily the Fibonacci sequence maps to C++ iterators; it works fine with C# and Java IEnumerable<T> and Iterable<T> though.)

始终不够爱げ你 2024-11-14 08:16:13

当您需要存储状态时(例如,当您计算斐波那契数,根据它执行某些操作,然后计算另一个数)时,您找到的解决方案是不错的,但是从代码中的两个位置使用它可能会很有趣结果。这是因为静态变量始终是相同的,无论从哪里调用它。相反,我建议:

class FiboNumbers {
  public:
    FiboNumbers() :
        x_(1), y_() {}

    int getNext() {
        x_ += y_;
        y_ = x_ - y_;
        return x_;
    }

  private:
    int x_, y_;
};

这提供了相同的状态保持功能,但允许您创建该类的多个实例,因此允许您使用不同的代码部分来计算自己的斐波那契数列。

小提示:我发布的代码将生成与您发布的示例相同的序列,但它将生成真正的斐波那契序列,以 0 1 1 2 开头...

The solution you found is decent for when you need to store the state (for example, when you calculate a Fibonacci number, do something based on it, and then calculate another), but using this from two places in your code will likely give funny results. This is because the static variables will always be the same, no matter from where you call it. I would instead suggest:

class FiboNumbers {
  public:
    FiboNumbers() :
        x_(1), y_() {}

    int getNext() {
        x_ += y_;
        y_ = x_ - y_;
        return x_;
    }

  private:
    int x_, y_;
};

This offers the same keeping-of-state, but allows you to create multiple instances of the class, therefore allowing you to have different parts of the code that calculate their own Fibonacci series.

Minor note: the code I posted will produce the same series as the example you posted, but it will produce the real Fibonacci sequence, which starts with 0 1 1 2...

稍尽春風 2024-11-14 08:16:13

我是一名 C++ 学生(学习 1.5 个月)。

请对我为斐波那契数列想到的这种不同方式提供反馈。

#include<iostream>

using namespace std;

void fibseries(long int n)
{
    double x=0;double y=1;
    for (long int i=1;i<=n;i++)
     {
        if(i%2==1)
         {
            cout<<x<<" ";
            x=x+y;
         } 
        else 
         {
            cout<<y<<" ";
            y=x+y;
         }
     }
}

main()
{
    long int n=0;
    cout<<"The number of terms ";
    cin>>n;
    fibseries(n);
    return 0;
}

I am a C++ student (1.5 months into it).

Give feedback to this different way I have thought of for Fibonacci series.

#include<iostream>

using namespace std;

void fibseries(long int n)
{
    double x=0;double y=1;
    for (long int i=1;i<=n;i++)
     {
        if(i%2==1)
         {
            cout<<x<<" ";
            x=x+y;
         } 
        else 
         {
            cout<<y<<" ";
            y=x+y;
         }
     }
}

main()
{
    long int n=0;
    cout<<"The number of terms ";
    cin>>n;
    fibseries(n);
    return 0;
}
何时共饮酒 2024-11-14 08:16:13

我不确定这个功能到底应该做什么。它
仅适用于您呈现的确切循环,并且正如其他人一样
指出,它只能工作一次。 (而且可能有一个错字
在你的循环中,因为你的完整程序输出 "0",并且
没有别的。)它比以下有什么优势:

int y = 0;
int x = 1;
for ( int i = 0; i < count; ++ i ) {
    std::cout << y <<std::endl;
    y = x + y;
    x = y - x;
}

?它更加复杂,健壮性差得多,而且用处也少得多。

I'm not sure what this function is really supposed to do. It
only works in the exact loop you present, and as others have
pointed out, it only works once. (And there's probably a typo
in your loop, since your complete program outputs "0", and
nothing else.) What advantage does it offer over:

int y = 0;
int x = 1;
for ( int i = 0; i < count; ++ i ) {
    std::cout << y <<std::endl;
    y = x + y;
    x = y - x;
}

? It's more complex, far less robust, and far less useful.

姐不稀罕 2024-11-14 08:16:13

如前所述,静态变量的优点原则上是计算序列的第 n 个元素更便宜,其中第 n - 1 个元素已经被评估过。

除了静态变量固有的问题之外,最大的缺点是您没有任何方法可以返回到序列中的较早点,也无法真正很好地控制您在序列中所处的位置。给定时间。

正如 Sevis 所推荐的那样,使用 class 无疑是实现这种类似静态方法的更好方法:这使一切变得更安全,为您提供了一种返回序列开始的简单方法(只需重新初始化对象),并且还可以实现进一步的功能,例如返回k步、查找当前位置等。

As was said before, the advantage of the static variables is, in principle, that it's cheaper to calculate the n -th Element of a sequence where the n - 1 -th has already been evaluated.

The big drawback, apart from the problems inherent to static variables, is that you don't have any way to get back to an earlier point in the sequence, nor do you really have a good control over where in the sequence you are at a given time.

Using a class, as recommended by Sevis, is certainly the better way of implementing such a static-like approach: this makes everything safer, gives you an easy way to get back to the sequence start (by simply reinitializing the object) and also makes it possible to implement further functionality, like going back k steps, looking up the present position, etc..

冷情 2024-11-14 08:16:13

我认为这种指针方法对您更有用。

void main()
{
    int i,p, *no,factorial,summ;

    int fib(int p);

    clrscr();

    printf("\n Enter The Number:");
    scanf("%d", no);
    printf("\n The Fibonnacci series: \n");

    for(i=0; i < *no; i++)
        printf("%d\n", fib(i));

    getch();
}

int fib(int p)
{
    if(p == 0)
        return(0);
    if(p >= 1 && p <= 2)
        return(1);
    else
        return(fib(p - 1) + fib(p - 2));
}

I think this pointer approach would be more useful for you.

void main()
{
    int i,p, *no,factorial,summ;

    int fib(int p);

    clrscr();

    printf("\n Enter The Number:");
    scanf("%d", no);
    printf("\n The Fibonnacci series: \n");

    for(i=0; i < *no; i++)
        printf("%d\n", fib(i));

    getch();
}

int fib(int p)
{
    if(p == 0)
        return(0);
    if(p >= 1 && p <= 2)
        return(1);
    else
        return(fib(p - 1) + fib(p - 2));
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文