Pregunta

¿Cómo haría cálculos con números extremadamente grandes en Java?

Yo he tratado long pero eso alcanza un máximo de 9223372036854775807, y cuando se usa un número entero no guarda suficientes dígitos y, por lo tanto, no es lo suficientemente preciso para lo que necesito.

¿Hay alguna forma de solucionar esto?

¿Fue útil?

Solución

Puede utilizar el BigInteger clase de números enteros y BigDecimal de números con dígitos decimales. Ambas clases se definen en java.math paquete.

Ejemplo:

BigInteger reallyBig = new BigInteger("1234567890123456890");
BigInteger notSoBig = new BigInteger("2743561234");
reallyBig = reallyBig.add(notSoBig);

Otros consejos

Utilice la BigInteger clase que es una parte de la biblioteca de Java.

http: //java.sun. com / J2SE / 1.5.0 / docs / api / java / matemáticas / BigInteger.html

Aquí está un ejemplo que pone grandes números muy rápidamente.

import java.math.BigInteger;

/*
250000th fib # is: 36356117010939561826426 .... 10243516470957309231046875
Time to compute: 3.5 seconds.
1000000th fib # is: 1953282128707757731632 .... 93411568996526838242546875
Time to compute: 58.1 seconds.
*/
public class Main {
    public static void main(String... args) {
        int place = args.length > 0 ? Integer.parseInt(args[0]) : 250 * 1000;
        long start = System.nanoTime();
        BigInteger fibNumber = fib(place);
        long time = System.nanoTime() - start;

        System.out.println(place + "th fib # is: " + fibNumber);
        System.out.printf("Time to compute: %5.1f seconds.%n", time / 1.0e9);
    }

    private static BigInteger fib(int place) {
        BigInteger a = new BigInteger("0");
        BigInteger b = new BigInteger("1");
        while (place-- > 1) {
            BigInteger t = b;
            b = a.add(b);
            a = t;
        }
        return b;
    }
}

Verificar BigDecimal y BigInteger.

import java.math.BigInteger;
import java.util.*;
class A
{
    public static void main(String args[])
    {
        Scanner in=new Scanner(System.in);
        System.out.print("Enter The First Number= ");
        String a=in.next();
        System.out.print("Enter The Second Number= ");
        String b=in.next();

        BigInteger obj=new BigInteger(a);
        BigInteger obj1=new BigInteger(b);
        System.out.println("Sum="+obj.add(obj1));
    }
}

En función de lo que está haciendo que le gustaría echar un vistazo a GMP (gmplib.org) que es una biblioteca de precisión múltiple de alto rendimiento. Para usarlo en Java que necesita envoltorios JNI alrededor de la biblioteca binaria.

Vea algunos de los códigos Alioth tiroteo para un ejemplo de su uso en lugar de BigInteger para calcular Pi a un número arbitrario de dígitos.

https: //benchmarksgame-team.pages .debian.net / benchmarksgame / programa / pidigits-java-2.html

utilizando el tipo de datos de cadena que resolver fácilmente este problema.

class Account{
      String acc_no;
      String name;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top