Problem Description
Recall the definition of the Fibonacci numbers:
f1 := 1
f2 := 2
fn := fn-1 + fn-2 (n >= 3)

Given two numbers a and b, calculate how many Fibonacci numbers are in the range [a, b].
 

 

Input
The input contains several test cases. Each test case consists of two non-negative integer numbers a and b. Input is terminated by a = b = 0. Otherwise, a <= b <= 10^100. The numbers a and b are given with no superfluous leading zeros.
 

 

Output
For each test case output on a single line the number of Fibonacci numbers fi with a <= fi <= b.
 

 

Sample Input
10 100 1234567890 9876543210 0 0
 

 

Sample Output
5 4
 

 

Source
   关键是用字符串保存数据,这些是斐波那契数,在第500个时就能达到100位以上的数了,即接下来就是大数加法的问题了。。。关键要细心啊。。。
代码:
#include <iostream>
#include <string>
#define N 500
using namespace std;

string *A = new string[N];
string Sum_calc(string s1,string s2)
{

    int
length;
   
    if
(s1.length()>=s2.length())
    {

        length=s1.length();
        string tmp(s1.length()-s2.length(),'0');
        s2=tmp+s2;
    }

    else

    {

        length=s2.length();
        string tmp(s2.length()-s1.length(),'0');
        s1=tmp+s1;
    }

    string sum(length,'0');
    int
carry = 0;    //carry
    for (int k=length-1;k!=-1;--k)
    {
       
        sum[k]=(s1[k]+s2[k]+carry-96)%10+48;
        carry=(s1[k]+s2[k]+carry-96>9);
    }

    if
(carry)
        sum='1'+sum;
   
    return
sum;

}

int
main()
{
 
   
    int
j,n,m;
    string s1,s2;
    string *A = new string[N];
    A[1]='1';
    A[2]='2';
    for
(int i=3; i<N; ++i)
    {

        A[i] = Sum_calc(A[i-2], A[i-1]);
    }

   while
(cin>>s1>>s2)  
   {

          n=0,m=0;
          if
(s1[0]=='0'&&s2[0]=='0')
           break
;
           if
(s1.length()==s2.length())
             m=1;//判断s1  s2的长度是否一样
       for
(j=1;;j++)
           {

            if
(m)//当s1  s2的长度一样
          {

              if
(A[j].length()==s1.length())
             {
   
                 if
((A[j].compare(s1)>=0)&&(A[j].compare(s2)<=0))
                    n++;
              }

              else
                 if
(A[j].length()>s1.length())
                   break
;
          }

          else //当s1  s2的长度不一样

           {

                if
(A[j].length()==s1.length())
             {
    if(A[j].compare(s1)>=0)
                    n++;
             }

             else if
(A[j].length()>s1.length()&&A[j].length()<s2.length())
               n++;
             else if
(A[j].length()==s2.length())
             {

                 if
(A[j].compare(s2)<=0)
                    n++;
               else
                    break
;
             }

             else
               if
(A[j].length()>s2.length())
                 break
;
            }
           }

           cout<<n<<endl;   
   }

     return
0;
}


posted on 2012-05-22 23:47  xinmenghuairi  阅读(324)  评论(0编辑  收藏  举报