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

博客主要讲述用字符串实现Fibonacci数列来求解大整数。在信息技术中,这种实现方式可解决大整数计算问题,避免数值溢出等情况,为相关计算提供有效方法。
// Fibonacci.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"


#include<stdio.h>
#include<string.h>
#include<iostream>
#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;

}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值