给定两个数字M和N,任务是检查第M个和第N个斐波那契数是否彼此完全除。
例子:
Input: M = 3, N = 6
Output: Yes
F(3) = 2, F(6) = 8 and F(6) % F(3) = 0
Input: M = 2, N = 9
Output: No
天真的方法是找到第N个和第M个斐波那契数,并检查它们是否被完全整除。
一种有效的方法是使用Fibonacci属性确定结果。如果m完美地除以n,则F m也可以完美地除以F n ,否则就不会。
例外:当N为2时,因为Fibo 2为1总是可能的,这将除以其他斐波那契数。
下面是上述方法的实现:
C++
// C++ program to check if
// M-th fibonacci divides N-th fibonacci
#include
using namespace std;
void check(int n, int m)
{
// exceptional case for F(2)
if (n == 2 || m == 2 || n % m == 0) {
cout << "Yes" << endl;
}
// if none of the above cases,
// hence not divisible
else {
cout << "No" << endl;
}
}
// Driver Code
int main()
{
int m = 3, n = 9;
check(n, m);
return 0;
}
Java
// Java program to check
// if M-th fibonacci
// divides N-th fibonacci
import java.io.*;
class GFG
{
static void check(int n, int m)
{
// exceptional case for F(2)
if (n == 2 || m == 2 ||
n % m == 0)
{
System.out.println( "Yes");
}
// if none of the above cases,
// hence not divisible
else
{
System.out.println( "No");
}
}
// Driver Code
public static void main (String[] args)
{
int m = 3, n = 9;
check(n, m);
}
}
// This code is contributed
// by anuj_67.
Python 3
# Python 3 program to
# check if M-th fibonacci
# divides N-th fibonacci
def check(n, m):
# exceptional case for F(2)
if (n == 2 or m == 2 or
n % m == 0) :
print( "Yes" )
# if none of the above
# cases, hence not divisible
else :
print( "No" )
# Driver Code
m = 3
n = 9
check(n, m)
# This code is contributed
# by Smitha
C#
// C# program to check
// if M-th fibonacci
// divides N-th fibonacci
using System;
class GFG
{
static void check(int n, int m)
{
// exceptional case for F(2)
if (n == 2 || m == 2 ||
n % m == 0)
{
Console.WriteLine( "Yes");
}
// if none of the above cases,
// hence not divisible
else
{
Console.WriteLine( "No");
}
}
// Driver Code
public static void Main ()
{
int m = 3, n = 9;
check(n, m);
}
}
// This code is contributed
// by anuj_67.
PHP
Javascript
输出:
Yes
时间复杂度: O(1)。
如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。