From f3ad87f0f957f395d4c3220845773b7d634582cd Mon Sep 17 00:00:00 2001 From: xw_y_am Date: Fri, 22 Feb 2019 02:59:26 +0800 Subject: [PATCH] add fibnacci serial --- fibnacci_serial/v.cpp | 90 +++++++++++++++++++++++++++++++++++++++++++ fibnacci_serial/v.py | 17 ++++++++ 2 files changed, 107 insertions(+) create mode 100644 fibnacci_serial/v.cpp create mode 100644 fibnacci_serial/v.py diff --git a/fibnacci_serial/v.cpp b/fibnacci_serial/v.cpp new file mode 100644 index 0000000..4086196 --- /dev/null +++ b/fibnacci_serial/v.cpp @@ -0,0 +1,90 @@ +#include +#include + +using namespace std; + +#define UNIT 100000000 +#define UNIT_LEN 8 +const char *zero = "00000000"; + +typedef vector BN; + +string BN_str(BN *b) +{ + string sn = to_string(b->at(b->size() - 1)); + for (int i = b->size() - 2; i >= 0; i--) { + string su = to_string(b->at(i)); + if (su.length() < UNIT_LEN) { + sn += (zero + su.length()); + } + sn += su; + } + return sn; +} + +int BN_len(BN *b) +{ + if (!b->size()) return 0; + int l = 0; + for (int h = b->back(); h; h /= 10) l += 1; + return (b->size() - 1) * UNIT_LEN + l; +} + +BN BN_init(int x) +{ + BN v; + v.push_back(x); + return v; +} + +void BN_merge(BN *a, BN *b) +{ + int carry_up = 0; + int ib = 0; + for (int ia = 0; ia < a->size(); ia++, ib++) { + carry_up += a->at(ia) + b->at(ib); + (*a)[ia] = carry_up % UNIT; + carry_up /= UNIT; + } + for (; ib < b->size(); ib++) { + carry_up += b->at(ib); + a->push_back(carry_up % UNIT); + carry_up /= UNIT; + } + for (; carry_up; carry_up /= UNIT) { + a->push_back(carry_up % UNIT); + } +} + +int BN_digit(BN *a, int n) +{ + string sn = BN_str(a); + if (n > sn.length()) return -1; + return sn[n - 1] - '0'; +} + +int digit_of_fib_digit(int n) +{ + BN a = BN_init(1); + BN b = BN_init(1); + BN *p = &a; + BN *q = &b; + for (;;) { + cout << BN_str(p) << endl; + int l = BN_len(p); + if (l >= n) { + return BN_digit(p, n); + } + n -= l; + BN_merge(p, q); + BN *t = p; + p = q; + q = t; + } +} + +int main() +{ + cout << digit_of_fib_digit(800) << endl; + return 0; +} diff --git a/fibnacci_serial/v.py b/fibnacci_serial/v.py new file mode 100644 index 0000000..4de1722 --- /dev/null +++ b/fibnacci_serial/v.py @@ -0,0 +1,17 @@ + +def gen_fib(): + a, b = 0, 1 + while True: + yield b + a, b = b, a + b + +def digit_in_fib(n): + for x in gen_fib(): + print(x) + s = str(x) + l = len(s) + if l >= n: + return s[n - 1] + n -= l + +print(digit_in_fib(800))