高精度运算(超大数字运算)

A Fibonacci sequence is calculated by adding the previous two members the sequence, with the first two members being both 1.
F(1) = 1, F(2) = 1, F(3) = 1,F(4) = 1, F(n>4) = F(n - 1) + F(n-2) + F(n-3) + F(n-4)
Your task is to take a number as input, and print that Fibonacci number.

Input

Each line will contain an integers. Process to end of file.

Output

For each case, output the result in a line.

Sample

InputcopyOutputcopy
 
100
 
4203968145672990846840663646 Note: No generated Fibonacci number in excess of 2005 digits will be in the test data, ie. F(20) = 66526 has 5 digits.

用二维数组来储存数字


#include<iostream>
#include<set>
#include<vector>
#include<algorithm>
#include<string>
#include<cstring>
#include<queue>
#include<map>
#include<math.h>
#include<stack>
#include<string.h>


using namespace std;
typedef long long LL;
const int MAXN = 1e8;
int f[10000][600];

void init() {
	for (int i = 1; i <= 4; i++) {
		f[i][0] = 1;
	}
	for (int i = 5, t = 0, b = 0; i < 10000-2; i++) {
		t = 0, b = 0;
		for (int j = 0; j < 600-3; j++) {
			t = f[i - 1][j] + f[i - 2][j] + f[i - 3][j] + f[i - 4][j] + b;
			f[i][j] = t % MAXN;
			b = t / MAXN;
		}
	}
}

int main() {
	init();
	int n = 0;
	while (scanf("%d", &n) != EOF) {
		int fl = 1;
		for (int i = 600-5; i >= 0; i--) {
			if (fl == 1 && f[n][i] == 0) {
				continue;
			}
			else if (fl == 1) {
				printf("%d", f[n][i]);
				fl = 0;
			}
			else {
				printf("%08d", f[n][i]);
			}
		}
		cout << endl;
	}
	return 0;
}

或是

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>

using namespace std;
typedef long long LL;
const int N = 10000, M = 3000;
char f[N][M+2];

void init();
void print(int I);


int main() {
	init();
	/*for (int i = 1; i < 100; i++)
		print(i);*/

	int n;
	while (cin >> n) {
		if (n > N)
			break;
		print(n);
	}
	return 0;
}


void print(int I) {
	int g = 0;
	for (int i = M; i >=0; i--) {
		if (f[I][i] == 0 && g == 0)
			continue;
		else {
			g = 1;
			printf("%d", (int)(f[I][i]));
		}
	}
	printf("\n");
}

void init() {
	memset(f, 0, sizeof(f));
	f[1][0] = 1;
	f[2][0] = 1;
	f[3][0] = 1;
	f[4][0] = 1;
	for (int i = 5; i < N; i++) {
		int jin = 0;
		for (int j = 0; j <=M; j++) {
			f[i][j] = f[i - 1][j] + f[i - 2][j] + f[i - 3][j] + f[i - 4][j] + jin;
			jin = f[i][j] / 10;
			f[i][j] %= 10;
		}
		if (f[i][M] != 0)
			break;
	}
}

posted @ 2023-07-11 18:36  Landnig_on_Mars  阅读(7)  评论(0编辑  收藏  举报  来源