HDU-1316 How Many Fibs? 大數、二分問題 (C語言)

來源:互聯網
上載者:User

先就題目意思做簡單介紹,題中要求在給定的兩個數a,b(a,b<=10^100)之間[a,b]計算有多少個斐波那契(Fibonacci)數,注意這裡約定:

f1 := 1
f2 := 2
fn := fn-1 + fn-2 (n >= 3)

基本思路如下:

  1.鑒於有多組測試資料且斐波那契數又是一組特殊的數組(每一項與前驅有一定的關係),採用打表的方式,將1-10^100之間所有的斐波那契數儲存起來.

  2.錄入兩個字串作為上下界.

  3.在斐波那契數組中檢索上下界的位置,直接求出中間存在斐波那契數的個數.

代碼如下:

#include<stdio.h>#include<string.h>#include<stdlib.h>#include<math.h> #define M 105char a[M+2],b[M+2];char book[1000][M+2];int cmp(char *s1,char *s2){for(int i=0;i<=M;++i){if(i==M){ return s1[i]-s2[i];//如果到最後一位相等,要保證返回0; }if(s1[i]==s2[i])continue;else{ return s1[i]-s2[i];}}} //一下兩個函數是二分尋找上下界的位置. //尋找原則是下界數組座標減一,上界數組座標加一 int find1(int i,char *x)    { int low=0,high=i,mid; //定義左右指標,中間指標 while(low<=high){mid=(low+high)/2;int t=cmp(book[mid],x); if(t>0)high=mid-1;//改變左右界,並位移(為了使左右指標交錯) else if(t==0) return mid-1;  elselow=mid+1;}  return high;   //跳出時, high 變數在左邊}int find2(int i,char *x){int low=0,high=i,mid;while(low<=high){mid=(low+high)/2;int t=cmp(book[mid],x); if(t>0) high=mid-1;  else if(t==0) return mid+1; else low=mid+1;  } return low; }int main(){int p=M,i=2;  //p用於標記最高位的位置 book[0][M]=1,book[1][M]=2;while(book[i-1][M-100]<=1){for(int j=M;j>=p;--j)book[i][j]=book[i-1][j]+book[i-2][j];for(int j=M;j>=p;--j){int c=book[i][j]/10;book[i][j]%=10;book[i][j-1]+=c;}     //即時進位操作 if(book[i][p-1]>0) //判斷是否最高位發生變化 --p;//如果當前的最高位的下一位不為零,則指標減一 ++i; }    while(scanf("%s%s",a,b),a[0]-'0'||b[0]-'0'){int cnt=0,p;int last1=strlen(a)-1;int last2=strlen(b)-1;for(int j=last1,k=M;j>=0;--j,--k){a[k]=a[j]-'0';a[j]=0;          //消除幹擾比較的因素,置零操作 } for(int j=last2,k=M;j>=0;--j,--k){b[k]=b[j]-'0';b[j]=0; } int l=find1(i-1,a); int r=find2(i-1,b); printf("%d\n",r-l-1);memset(a,0,sizeof(a));  //清除上一次操作的資料遺留 memset(b,0,sizeof(b)); }     return 0;}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.