0%

POJ2413 How many Fibs?【高精度】

2018年8月3日 下午3:54

这篇文章中有详细的分析步骤:
POJ2413 How many Fibs?【高精度】【二分】 - CSDN博客

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
// 数组长度的设置
// 第480个fibonacci数是101位。这是设置550*130的原因
const int MAXN = 550;
const int MAXNLEN = 130;
//注意:在使用数组模拟大数求和时,这里是int类型
// 一个一维数组 = 一个int类型的数
int F[MAXN][MAXNLEN];
//这个Fi的目的是为了保存出去前导0的数据
char Fi[MAXN][MAXNLEN],ans[MAXN];

void Fibo()
{
F[1][0] = 1;
F[2][0] = 2;
for(int i = 3; i <= 500; ++i)
{
for(int j = 0; j <= 110; ++j)
{
F[i][j] = F[i][j] + F[i-1][j] + F[i-2][j];
// 模拟进位
if(F[i][j] >= 10)
{
F[i][j+1] += F[i][j]/10;
F[i][j] %= 10;
}
}
}
//去除前导0
for(int i = 1; i <= 500; ++i)
{
int j;
for(j = 110; j >= 0; j--)
if(F[i][j] == 0)
continue;
else
break;
int k = 0;
for(; j >= 0; j--)
Fi[i][k++] = F[i][j] + '0';
F[i][k] = '\0';
}
}

int cmp(char *A,char *B)
{
int LenA = strlen(A);
int LenB = strlen(B);
if(LenA != LenB)
return LenA > LenB ? 1 : -1;
else
return strcmp(A,B);
}
//使用二分法查找,返回low,flag是一个是否直接找到Num的标志
// 二分法直接按现实步骤模拟就行了
int Search(char *Num,bool &flag)
{
int low = 1;
int high = 480;
while(low <= high)
{
int mid = (low+high)/2;
int res = cmp(Num,Fi[mid]);
if(res == 0)
{
flag = 1;
return mid;
}
else if(res < 0)
high = mid - 1;
else
low = mid + 1;
}
return low;
}
char A[MAXNLEN],B[MAXNLEN];

int main()
{
Fibo();
while(~scanf("%s %s",A,B))
{
if(strcmp(A,"0")==0 && strcmp(B,"0") == 0)
break;

bool FlagA = 0;
bool FlagB = 0;
int Left = Search(A,FlagA);
int Right = Search(B,FlagB);

if(FlagB)
printf("%d\n",Right-Left+1);
else
printf("%d\n",Right-Left);
}
return 0;
}