HDOJ 1021 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
这题测试数据很大,单纯根据定义运算的话会溢出,递归当然也会超时,这种题一般有特殊解法或着是有什么规律,我们可以写出前几项观察观察。
通过找规律,发现
n 0 1 2 3 4 5 6 7 8 9 10
f(n) 7 11 18 29 47 76 123 199 322 521 843
余数 1 2 0 2 2 1 0 1 1 2 0
输出 no no yes no no no yes no no no yes
每8个数是一个循环,%8 == 2 和 %8 == 6的时候f(n)%3 == 0
那么我们可按照这个规律写代码了。
#include <stdio.h>
int main(void)
{
int n;
while(scanf("%d", &n) != EOF)
{
if(n % 8 == 2 || n % 8 == 6)
printf("yes\n");
else
printf("no\n");
}
return 0;
}
不难看出每四个数,输出一个yes也可以根据这个规律写代码
#include <iostream>
using namespace std;
int main()
{
int n;
while (cin >> n)
{
if ((n + 2) % 4 == 0) //从第二个数之后开始规律成立
puts("yes"); //puts()自带换行
else
puts("no");
}
return 0;
}