C ++处理大数 [英] C++ Handling big numbers

查看:61
本文介绍了C ++处理大数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我必须为我的c ++类做简单的任务.有两个功能,第一个是斐波那契数列,第二个是一些随机数列(查找 e ).看起来像这样:

Okay, I have to do simple task for my c++ class. Two functions, first is Fibonacci sequence, second some random sequence (finding e). It looks like this:

#include <stdio.h>
#include <cstdlib>
#include <string>
#include <math.h>

void fib(int number)
{
    int a=0, b=1;
    printf("%d\n", a); 
    for (; number>0; number--)
    {
        printf("%d\n", b);
        b+=a;
        a = b-a;
    }
}

void e_math(unsigned int number)
{
    for (double n = 1; number>0; number--, n++)
    {
        printf("%f\n", pow((1+1/n), n));
    }
}

int main(int argc, char** argv)
{
    if (std::string(argv[2])=="f") fib(atoi(argv[1])-1);
    if (std::string(argv[2])=="c") e_math(atoi(argv[1])-1);
    else printf("Bad argument\n");
}

所以最后我做了 g ++ main.cpp -o app; ./app 10 f .它工作得很好.但是当我想到:嗯,也许让我们检查更大的数字,然后再加上50个就搞砸了.我的意思是,它对大约40个序列号(用Python检查过)很有用,但是随后它开始对 printf()负数进行了处理.我发现它大概在 int 范围内.所以我将 int a = 0,b = 1 更改为 long long a = 0,b = 1 ,但是它仍然打印相同的东西(我仍然使用 printf(%d ..),因为%lld 不起作用

So at the end I did g++ main.cpp -o app;./app 10 f. It worked perfectly. But when I thought: Hmm, maybe lets check for bigger number, and added 50 it just messed up. I mean it did good for about 40 sequence numbers (checked with Python), but then it started to printf() negatives etc. I figured it's probably about int range. So I changed int a=0, b=1 to long long a=0, b=1, but still it prints the same (I still use printf("%d..), because %lld does not work

推荐答案

注释中包含一些信息,告诉您如何正确打印 long long ,以便您可以从整个范围中受益.但是,正如blazs在回答中所说的那样,您不会走得更远(它将在无符号64位上循环n = 94).

There are information in comments telling you how to be able to print long long correctly so that you can benefit from the whole range. However, as said blazs in his answer, you will not go much further (it will cycle for n=94 on unsigned 64 bits).

如果要处理更大的斐波那契数(实际上是任意大数),可以使用

If you want to handle much bigger Fibonacci numbers (in fact, arbitrary large numbers) you can use boost::multiprecision.

例如:

#include <boost/multiprecision/gmp.hpp>  

boost::multiprecision::mpz_int fib(boost::multiprecision::mpz_int number)
{
    boost::multiprecision::mpz_int a=0, b=1;
    for (; number>0; number--)
    {
        b += a;
        a = b-a;
    }
    return a;
}

int main()
{
    std::cout << fib(500);
}

构建时需要与gmp链接.例如:

You'll need to link with gmp when building. For example:

g++ -o fib fib.cc -lgmp
./fib
139423224561697880139724382870407283950070256587697307264108962948325571622863290691557658876222521294125

这篇关于C ++处理大数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆