如何计算数字达到千位数

时间:2012-07-21 12:52:06

标签: math language-agnostic

何在具有2GB RAM的32位计算机上进行计算。 当我进行长数运算时,程序开始给出垃圾值。但我想计算数字达到数万个数字。接受任何语言。

9 个答案:

答案 0 :(得分:6)

使用Java的BigInteger几乎立即执行:

import java.math.BigInteger;
import java.util.Random;

public class Int10k {

    public static final void main(String[] args) {
        BigInteger  a, b, c;
        Random rnd;

        // Here I'll create two random 40,000-bit numbers (that's
        // rather more than 10,000 decimal digits) and add them
        // together. For specific numbers, you can use the
        // BigInteger(String) constructor, which creates a
        // BigInteger based on a String of digits.
        rnd = new Random();
        a = new BigInteger(40000, rnd);
        b = new BigInteger(40000, rnd);
        c = a.add(b);

        System.out.println(a);
        System.out.println("+");
        System.out.println(b);
        System.out.println("=");
        System.out.println(c);
    }
}

答案 1 :(得分:3)

您可以使用Java BigInteger或任何其他Big Integer实现

示例:

BigInteger left = new Biginteger("1845618948745415218748");
BigInteger right = new BigInteger("1845452132132132123132123123");

out.println(left.add(right));

答案 2 :(得分:3)

此处使用的库是BC Math。它默认包含在PHP中。

$big_int1 = "";
$big_int2 = "";

for( $i = 0; $i < 10000; ++$i ) {
    $big_int1 .= mt_rand(0,9);
    $big_int2 .= mt_rand(0,9);
}//0.019520044326 seconds or 20 milliseconds

echo bcadd( $big_int1, $big_int2 ); //0.00037407875061035 seconds or 374 microseconds

立刻为我执行。无论如何,字符串连接/随机数生成是瓶颈。

答案 3 :(得分:2)

以下是各种语言的便捷链接:

  • Python(内置)
  • C / C ++ - GMP,可能是最有效的通用任意精度数字库
  • .NET 4(内置)
  • .NET - GnuMpDotNet - 使用GMP,因此也非常有效,但由于操作员重载等原因而更易于使用
  • Java(内置)
  • PHP - BC Math

答案 4 :(得分:1)

这不是一个语言问题,它是一个数学问题:http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic一个众所周知的,并且有大量的编程库可以为你解决它。

答案 5 :(得分:1)

所有Common Lisp实现都包含任意长度的整数。通常,实现向C库提供处理它,但在Lisp中工作更方便。

例如,看看Clisp,SBCL或CMUCL(网络搜索会找到这些项目的主页)。

答案 6 :(得分:0)

问题是如此抽象,是的,可以实现这样的计算器。在某些时候,您可能不得不依赖磁盘缓存并手动实现操作,而不是依赖于现有的类(例如Java的BigInteger),但它在技术上是可行的。

答案 7 :(得分:0)

是的,有可能。这是一个公共领域的c ++库,仅供参考:https://mattmccutchen.net/bigint/

答案 8 :(得分:0)

这里存在很好的算法,你可以使用define 2 array [0-9]并根据每个结果定义一个新数组:

{0,1,2,3,4,5,6,7,8,9}
{0,1,2,3,4,5,6,7,8,9}
/////

然后你可以定义一个放置+结果的二维数组:

0 1 ....
1 ...

*和/和etc相同,然后你读取字符串类型和创建和字符串输出。