📌  相关文章
📜  如何检查给定数字是否为斐波那契数的C ++程序?

📅  最后修改于: 2021-05-31 17:10:45             🧑  作者: Mango

给定数字“ n”,如何检查n是否为斐波那契数。前几个斐波那契数是0、1、1、2、3、5、8、13、21、34、55、89、141 、.

例子 :

Input : 8
Output : Yes

Input : 34
Output : Yes

Input : 41
Output : No

以下是有关斐波那契数的一个有趣属性,也可以用于检查给定数字是否为斐波那契。
当且仅当(5 * n 2 + 4)或(5 * n 2 – 4)中的一个或两个是一个完美的正方形时,这个数字才是斐波那契数(来源:Wiki)。

// C++ program to check if x is a perfect square
#include 
#include 
using namespace std;
  
// A utility function that returns true if x is perfect square
bool isPerfectSquare(int x)
{
    int s = sqrt(x);
    return (s * s == x);
}
  
// Returns true if n is a Fibinacci Number, else false
bool isFibonacci(int n)
{
    // n is Fibinacci if one of 5*n*n + 4 or 5*n*n - 4 or both
    // is a perferct square
    return isPerfectSquare(5 * n * n + 4) || isPerfectSquare(5 * n * n - 4);
}
  
// A utility function to test above functions
int main()
{
    for (int i = 1; i <= 10; i++)
        isFibonacci(i) ? cout << i << " is a Fibonacci Number \n"
                       : cout << i << " is a not Fibonacci Number \n";
    return 0;
}
输出:
1 is a Fibonacci Number 
2 is a Fibonacci Number 
3 is a Fibonacci Number 
4 is a not Fibonacci Number 
5 is a Fibonacci Number 
6 is a not Fibonacci Number 
7 is a not Fibonacci Number 
8 is a Fibonacci Number 
9 is a not Fibonacci Number 
10 is a not Fibonacci Number

请参阅有关如何检查给定数字是否为斐波纳契数的完整文章?更多细节!

想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”