📌  相关文章
📜  检查第M个斐波那契数是否除以第N个斐波那契数(1)

📅  最后修改于: 2023-12-03 15:40:35.780000             🧑  作者: Mango

检查第M个斐波那契数是否除以第N个斐波那契数
简介

本文介绍如何检查第M个斐波那契数是否能被第N个斐波那契数整除。斐波那契数列是一个由1和1开始的数列,其后每一项都等于前两项之和,即 F(i) = F(i-1) + F(i-2)。该数列前几项为,1, 1, 2, 3, 5, 8, 13, 21, 34, ...。

算法思路

首先,我们需要先求出第M和第N个斐波那契数。可以使用递归算法或迭代算法来求解。然后,使用求余运算符 % 来判断第M个斐波那契数是否能被第N个斐波那契数整除。

代码实现

Python

def fibonacci(n):
    if n == 1 or n == 2:
        return 1
    else:
        return fibonacci(n-1) + fibonacci(n-2)

m = 10
n = 6
if fibonacci(m) % fibonacci(n) == 0:
    print(f"The {m}th Fibonacci number can be divided by the {n}th Fibonacci number.")
else:
    print(f"The {m}th Fibonacci number cannot be divided by the {n}th Fibonacci number.")

C++

#include <iostream>
using namespace std;

int fibonacci(int n)
{
    if (n == 1 || n == 2)
        return 1;
    else
        return fibonacci(n - 1) + fibonacci(n - 2);
}

int main()
{
    int m = 10, n = 6;
    if (fibonacci(m) % fibonacci(n) == 0)
        cout << "The " << m << "th Fibonacci number can be divided by the " << n << "th Fibonacci number." << endl;
    else
        cout << "The " << m << "th Fibonacci number cannot be divided by the " << n << "th Fibonacci number." << endl;

    return 0;
}
结论

通过求余运算符 % 判断第M个斐波那契数是否能被第N个斐波那契数整除,可以得出结论。