HDU1021 ZOJ2060 Fibonacci Again【斐波拉契数列+模除】

Fibonacci Again

Time Limit: 2 Seconds      Memory Limit: 65536 KB

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



Author: Leojay
Source: ZOJ Monthly, December 2003



问题链接HDU1021 ZOJ2060 Fibonacci Again

问题描述参见上文。

问题分析这是一个有关数列与模除的问题。

斐波拉契数列是人们熟悉的。如果计算这个数列则各项的值会很大,很难处理。这个问题是给一个n,问第n项f(n)能否被3整除。

根据数论的知识可知,模3的余数值只有0、1和2。f(n)(mod 3)(f(n-2)+f(n-1))(mod 3)(f(n-2)(mod 3) + f(n-1)(mod 3))(mod 3)。另外,若对于正整数k和m,若f(k-2)=f(m-2)且f(k-1)=f(m-1),则f(k)=f(k-2)+f(k-1)=f(m-2)+f(m-1)=f(m),即如果k和m的前两项完全相同,则f(k)=f(m)。这样的数列,若干项之后,其值会循环出现,所以不必将其所有的项都算出来,只需要算出第一个循环的各个项即可。

因此,只需要构建一个短数列,其值为3的余数,并且用它来判定第n项能否被3整除。

解决这个问题之前,需要做一些准备。

程序说明

先编写一个试探程序,用于计算本问题的模3的数列的前若干项,找出其循环规律。

然后写出解决问题程序。


试探程序如下(递推计算)

#include <stdio.h>

#define DIVIDENUM 3

int fibagain(long n)
{
    if(n==0)
        return 7 % 3;
    else if(n==1)
        return 11 % 3;
    else {
        long i=0, f0 = 7, f1 = 11, temp;
        f0 %= DIVIDENUM;
        f1 %= DIVIDENUM;
        for(;;) {
            if(++i == n)
                return f1;
            else {
                temp = (f0+f1) % DIVIDENUM;
                f0 = f1;
                f1 = temp;
            }
        }
    }
}

void trypg()
{
    int i;

    for(i=0; i<=25; i++)
        printf("%d ", fibagain(i));
    printf("
");
}

试探程序的运行结果如下(前26项):

1 2 0 2 2 1 0 1 1 2 0 2 2 1 0 1 1 2 0 2 2 1 0 1 1 2

从中可以看出,该数列每8项就会出现循环,即f(n)=f(n mod 8)。只要事先计算前8项,其余各项用f(n mod 8)来计算。


AC的C语言程序如下:

/* HDU1021 Fibonacci Again */

#include <stdio.h>

int main(void)
{
    int t[] = {0, 0, 1, 0, 0, 0, 1, 0};

    long n;
    while(scanf("%ld", &n) != EOF) {
        if(t[n % 8])
            printf("yes
");
        else
            printf("no
");
    }

    return 0;
}