UVA 10579 Fibonacci Numbers(高精度加法)

discription

一个斐波那契数列

f(1)=1,f(2)=1,f(n>2)=f(n1)+f(n2)

input

输入一个n

output

输出相应的斐波那契数列数字

Sample Input

3
100

Sample Output

2
354224848179261915075

注意:没有生成的斐波那契数列数字超过100位数字。

solution

高精度加法

code

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <cstring>
#include <string>

using namespace std;
string add(string str1, string str2) //高精度加法
{
    string str;

    int len1 = str1.length();
    int len2 = str2.length();
    //前面补0,弄成长度相同
    if (len1 < len2)
    {
        for (int i = 1; i <= len2 - len1; i++)
            str1 = "0" + str1;
    }
    else
    {
        for (int i = 1; i <= len1 - len2; i++)
            str2 = "0" + str2;
    }
    len1 = str1.length();
    int cf = 0;
    int temp;
    for (int i = len1 - 1; i >= 0; i--)
    {
        temp = str1[i] - '0' + str2[i] - '0' + cf;
        cf = temp / 10;
        temp %= 10;
        str = char(temp + '0') + str;
    }
    if (cf != 0)
        str = char(cf + '0') + str;
    return str;
}
int main()
{
    // freopen("in.txt", "r", stdin);
    int n;
    while (~scanf("%d", &n))
    {
        string n1 = "1", n2 = "1", n3 = "0";
        int cnt = n - 2;
        for (; cnt > 0; cnt--)
        {
            n3 = add(n1, n2);
            n1 = n2, n2 = n3;
        }
        if (n == 1 || n == 2)
            printf("1\n");
        else
            cout << n3 << '\n';
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值