斐波那契数列的修改

问题描述 投票:0回答:1

(C++实现) 斐波那契数列表示为 0 1 1 2 3 5 8 13 21 34 55 ...... 假设我们有一个称为“Varionacci Series”的变体,其中前 3 个数字是 固定,下一个数字是通过添加前两个数字来生成的,即 2、2、3、4、5、7、9、12、16、21、28、 找到计算斐波那契数列的两种算法(迭代和递归),编写代码 算法以这样的方式提供一个数字作为参数,并打印直到该数字的系列 值,即 CalculateVarionacci(5) 应该导致打印 2, 2, 3, 4, 5

我尝试了很多,但没有得到想要的结果。
这是我的代码

#include <iostream>
#include <chrono>  // For time measurement

void CalculateVarionacciIterative(int n) {
    // First three fixed numbers
    int a = 2, b = 2, c = 3;

    // Print the first three numbers
    if (n >= 1) std::cout << a << " ";
    if (n >= 2) std::cout << b << " ";
    if (n >= 3) std::cout << c << " ";

    // Calculate remaining terms iteratively using correct updating of previous numbers
    for (int i = 4; i <= n; i++) {
        int next = a + b;  // Sum of the previous two numbers (a and b)
        std::cout << next << " ";
        // Shift the values to move forward in the sequence
        a = b;
        b = next;
    }
    std::cout << std::endl;
}

int main() {
    int n = 5;  // You can change n to any number of terms you want

    auto start = std::chrono::high_resolution_clock::now();
    CalculateVarionacciIterative(n);
    auto end = std::chrono::high_resolution_clock::now();

    std::chrono::duration<double> elapsed = end - start;
    std::cout << "Time taken for iterative approach: " << elapsed.count() << " seconds\n";

    return 0;
}
c++ fibonacci
1个回答
0
投票

您的代码几乎是正确的,您的错误是您总是根据函数中的

a
b
进行计算,因此第一个元素将等于前两个元素的总和,而不是第二个元素的总和第三。这就是您如何能够迭代地实现您想要的目标:

void CalculateVarionacciIterative(int n) {
    // First three fixed numbers
    int a = 2, b = 2, c = 3;

    // Print the first three numbers
    if (n >= 1) std::cout << a << " ";
    if (n >= 2) std::cout << b << " ";
    if (n >= 3) std::cout << c << " ";

    // Calculate remaining terms iteratively using correct updating of previous numbers
    for (int i = 4; i <= n; i++) {
        int next = b + c;  // Sum of the previous two numbers (b and c)
        std::cout << next << " ";
        // Shift the values to move forward in the sequence
        b = c;
        c = next;
    }
    std::cout << std::endl;
}

这就是递归实现它的方法:

int CalculateVarionacciRecursive(int n, bool print = false) {
    if (n == 3) {
        if (print) cout << "2 2 3 ";
        return 3;
    } else if (n == 2) {
        if (print) cout << "2 2 ";
        return 2;
    } else if (n == 1) {
        if (print) cout << "2 ";
        return 2;
    } else {
        int num = CalculateVarionacciRecursive(n - 2, false) + CalculateVarionacciRecursive(n - 1, print);
        if (print) cout << num << " ";
        return num;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.