程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> hdu 1250 Hats Fibonacci(高精度加法+縮進+斐波那契數)

hdu 1250 Hats Fibonacci(高精度加法+縮進+斐波那契數)

編輯:C++入門知識

題目大意:求一個斐波那契數列的第n 項, n的上限是10000.

 


解題思路:因為本題的上限是10000,所以對於高精度要進行縮進。

 

#include <iostream>
#include <string.h>
using namespace std;

const int MAXN = 100000000;
const int N = 500;
const int M = 10000;

struct bign {
    int len;
    int s[N];

    bign() {
	this -> len = 1;
	memset(s, 0, sizeof(s));
    }
    bign (int number) {*this = number;}
    bign (const char* number) {*this = number;}

    bign change(bign cur) {
	bign now;
	now = cur;
	for (int i = 0; i < cur.len; i++)
	    now.s[i] = cur.s[cur.len - i - 1];
	return now;
    }

    void delZore() {	// 刪除前導0.
	bign now = change(*this);
	while (now.s[now.len - 1] == 0 && now.len > 1) {
	    now.len--;
	}
	*this = change(now);
    }

    void put() {    // 輸出數值。
	delZore();
	printf("%d", s[0]);
	for (int i = 1; i < len; i++)
	    printf("%08d", s[i]);
    }

    bign operator = (const char *number) {
	memset(s, 0, sizeof(s));
	int dist = strlen(number);
	int k = dist % 8;
	for (int i = 0; i < k; i++)
	    s[0] = s[0] * 10 + number[i] - '0';
	int cnt = 0;
	for (int i = k; i < dist; i++, cnt++)
	    s[cnt / 8 + 1] = s[cnt / 8 + 1] * 10 + number[i] - '0';
	len = cnt / 8 + 1;
	return *this;
    }

    bign operator = (int number) {
	char string[N];
	sprintf(string, "%d", number);
	*this = string;
	return *this;
    }

    bign operator + (const bign &cur){  
	bign sum, a, b;  
	sum.len = 0;
	a = a.change(*this);
	b = b.change(cur);

	for (int i = 0, g = 0; g || i < a.len || i < b.len; i++){  
	    int x = g;  
	    if (i < a.len) x += a.s[i];  
	    if (i < b.len) x += b.s[i];  
	    sum.s[sum.len++] = x % MAXN;  
	    g = x / MAXN;  
	}  
	return sum.change(sum);  
    } 
};

bign num[M + 10];
int main() {
    int n;
    num[1] = num[2] = num[3] = num[4] = 1;
    for (int i = 5; i < M + 5; i++)
	num[i] = num[i - 1] + num[i - 2] + num[i - 3] + num[i - 4];
    while (scanf("%d", &n) == 1) {
	num[n].put();
	printf("\n");
    }
    return 0;
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved