字符串实现Fibonacci数列求大整数

// Fibonacci.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"


#include
#include
#include
#define MAX 102
using namespace std;
void add(char s1[], char s2[], char ans2[])
{
    char ans[MAX];
    int i, j, x, y, k = 0, l = 0;
    for (i = strlen(s1) - 1, j = strlen(s2) - 1; i >= 0 && j >= 0; i--, j--)
    {
        x = s1[i] - '0';
        y = s2[j] - '0';
        ans[l++] = (x + y + k) % 10 + '0';
        k = (x + y + k) / 10;
    }
    while (i >= 0)
    {
        x = s1[i] - '0';
        ans[l++] = (x + k) % 10 + '0';
        k = (x + k) / 10;
        i--;
    }
    while (j >= 0)
    {
        y = s2[j] - '0';
        ans[l++] = (y + k) % 10 + '0';
        k = (y + k) / 10;
        j--;
    }
    if (k>0)
        ans[l++] = '1';
    ans[l] = '\0';
    for (i = strlen(ans) - 1, l = 0; i >= 0; --i) {
        ans2[l++] = ans[i];
    }
    ans2[l] = '\0';
}


int main() {
    char pre[MAX];
    memset(pre, '\0', MAX * sizeof(char));
    pre[0] = '1';
    char mid[MAX];
    memset(mid, '\0', MAX * sizeof(char));
    mid[0] = '1';
    char result[MAX];
    memset(result, '\0', MAX * sizeof(char));
    int i, j, count = 2;
    printf("1\n1\n");
    for (i = 2; i<100; ++i)
    {
        add(pre, mid, result);
        count++;
        for (j = 0; j<strlen(result); ++j)
        {
            printf("%c", result[j]);
        }
        printf("\n");
        memset(pre, '\0', MAX * sizeof(char));
        strcpy_s(pre, mid);
        memset(mid, '\0', MAX * sizeof(char));
        strcpy_s(mid, result);

    }
    printf("count:%d", count);
    cin.clear();
    cin.sync();
    cin.get();
    return 0;

}

字符串实现Fibonacci数列求大整数_第1张图片

你可能感兴趣的:(Algorithms,and,Data,Structures,c和c++)