杭电OJ 1021(找规律)

题目如下:

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
    对于这一题,最开始的想法当然是用函数,递归直接算(这个显然不太现实也可以直接不看,跳到下面):

#include <iostream>
using namespace std;
int f(int a)
{
    int b;
    if(a==0)
    {
        b=7;
    }
    else if(a==1)
    {
        b=11;
    }
    else if(a>=2)
    {
        b=f(a-1)+f(a-2); //递归
    }
    return b;
}
int main()
{
    int n;
    while(cin>>n)
    {
        int m=f(n); //调用函数
        if(m%3==0)
        {
            cout<<"yes"<<" "<<m<<endl;
        }
        else
        {
            cout<<"no"<<" "<<m<<endl;
        }
    }
    return 0;
}

很显然,这样的做法在n变大的时候就会超时,这也是递归的占内存耗时间的一个很好的例子。至于迭代,我在看到超时之后,有点想法,但是发现这一题的特殊在于,每一个结果是否能被3整除是有规律的。
也就是,带入值就会发现:
0 no
1 no
2 yes
3 no
4 no
5 no
6 yes
...
10 yes
...
14 yes
...
18 yes
...
这样,规律就出来了。
从2开始,每隔三个数就会得到一个yes,那么我们由此可以得出一个肯定不会超时的代码:

#include <iostream>
using namespace std;
int main()
{
    int n;
    while(cin>>n)
    {
        if((n-2)%4==0)  //从2开始的之后的第四个数可以被三整除
        {
            cout<<"yes"<<endl;
        }
        else
        {
            cout<<"no"<<endl;
        }
    }
    return 0;
}

附上C语言的写法:

#include <stdio.h>
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF) 
    {
        if((n-2)%4==0)   //从2开始的之后的第四个数可以被三整除
        {
            printf("yes\n");
        }
        else
        {
            printf("no\n");
        }
    }
    return 0;
}

 

 

 

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值