hdoj1021 Fibonacci Again

題目:

Problem Description
There are another kind of Fibonacci numbers: F(0) = 7, F(1) = 11, F(n) = F(n-1) + F(n-2) (n>=2).
Input
Input consists of a sequence of lines, each containing an integer n. (n < 1,000,000).
Output
Print the word "yes" if 3 divide evenly into F(n).
Print the word "no" if not.
Sample Input
0
1
2
3
4
5
Sample Output
no
no
yes
no
no
no

此題與斐波拉契數(shù)列有點相似,但是如果是一個一個求出來打表再判斷它是否被3整除,肯定會出錯(因為此題n的值可能很大,求出來的值可能會爆long long)。但此題可以每次對結(jié)果模3,這樣就可以了。

參考代碼:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
const int N = 1000000+5;
typedef long long ll;
using namespace std;
ll num[N];
void dabiao() {
    num[0] = 7 % 3;
    num[1] = 11 % 3;
    for (int i = 2;i <= 1000000;++i) {
        num[i] = (num[i-1] + num[i-2]) % 3;
    }
}
int main() {
    dabiao();
    int n;
    while (scanf("%d", &n) != EOF) {
        if (num[n] == 0) printf("yes\n");
        else printf("no\n");
    }
    return 0;
}

另外,我在網(wǎng)上看到了一種找規(guī)律的方法,可以不打表。
我們可以先算出前面多組數(shù)據(jù)的值,然后就可以發(fā)現(xiàn)規(guī)律:
每8個數(shù)據(jù)一組,結(jié)果我們發(fā)現(xiàn):
根據(jù)公式求出來的結(jié)果模3的余數(shù)是:1 2 0 2 2 1 0 1.
這八個數(shù)字模8的結(jié)果是:0 1 2 3 4 5 6 7 8.

規(guī)律:給定的數(shù)模8的結(jié)果只要是2或6,根據(jù)公式求出來的數(shù)就一定能被3整除。

參考代碼:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
void judge(int num) {
    num = num % 8;
    if (num == 2 || num == 6) {
        printf("yes\n");
    }
    else {
        printf("no\n");
    }
}
int main() {
    int num;
    while (scanf("%d", &num) != EOF) {
        judge(num);
    }
    return 0;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容