C 斐波那契程序

C++ Fibonacci Program

本文关键字:程序      更新时间:2023-10-16

c 程序帮助您好,我正在编写一个C 程序,以打印出几个主要的斐波那契号。该程序打印出8个数字,而不仅仅是那些是素数的数字。可以帮我找出正在发生的事情

#include <iostream>
#include <cmath>
using namespace std;
//fibonacci function
int fibonacci(int x) {
if ((x == 1) || (x == 2)) { return 1; }
return  fib(x - 1) + fib(x - 2);
}
 //prime test bool function
bool is_prime(double n) {
for (int i = 2; i <= sqrt(n); i++) {
    if (n % i != 0) { return true; }
    else { return false; }
}

}

// main function 
int main (){
int y = 1;
int c = 0;
while (y >= 0) {
fibonacci(y);
if ((is_prime(true)) && (fibonacci(y) != 1)) {
cout <<  fib(y) << " ";
count++;
if (c >= 8) { return 0; }
        }
y++;

}}

返回0;}


您的代码上面使用该函数的双人名称,并且您使用c,而您可能表示count

is_prime函数逻辑应采用int,并且可以重写函数逻辑,以查找显示数字不是Prime的值。

最后,使用斐波那契函数的递归是详尽的。最好使用普通循环。

对您的代码检查此代码:

#include <iostream>
#include <cmath>
using namespace std;
int fib(int x)
{
    int first = 0, second = 1, sum = 0;
    if ((x == 1) || (x == 2)) { return 1; }
    for (int i = 2; i <= x; ++i)
    {
        sum = first + second;
        first = second;
        second = sum;
    }
    return sum;
}
bool is_prime(int n) // n should be int not double
{
    for (int i = 2; i <= sqrt(n); i++)
        if (n % i == 0)
            return false; // you should look for what breaks the condition
    return true; // if nothing break the condition you return true
}
int main ()
{
    for (int i = 1; i <= 8; ++i)
    {
        int f = fib(i);
        if (is_prime(f))
            cout << f << " ";
    }
}

您的is_prime()功能有一个逻辑问题,并且似乎正在返回相反的输入数字评估。尝试以下内容:

bool is_prime(int n) {
    for (int i=2; i <= sqrt(n); i++) {
        // if input divisible by something other than 1 and itself
        // then it is NOT prime
        if (n % i == 0) {
            return false;
        }
    }
    // otherwise it is prime
    return true;
}

这是一个演示,显示重构的is_prime()功能正常工作:

rextester

然后,您可以将此功能与fibonacci编号生成器一起使用,以查找前8个Prime fibonacci编号:

int c = 0;
int y = 1;
do {
    int fib = fibonacci(y);
    ++y;
    if (is_prime(fib)) {
        cout << fib << " ";
        ++c;
    }
} while (c < 8);

作为旁注,您的fibonacci()功能使用递归,并且对于大量输入而言,它的扩展不佳。考虑在那里使用动态编程来显着提高性能。

使用iS_prime((函数中的问题的tim biegeleisen答案。

但是,您根本没有检查fibonacci编号,始终以相同的值 is_prime(true)调用is_prime。除此之外,在当前实施中,周期将永远无法完成。尝试考虑以下循环:

while (y >= 0) {
    double fib = fibonacci(y);
    if ( is_prime(fib) && (fib != 1) ) {
        cout <<  fib << " ";
        c++;
        if (c >= 8) { return 0; }
    }
    y++;
}