문제

Java에서 매우 많은 숫자로 계산을하는 방법은 무엇입니까?

나는 시도했다 long 그러나 그것은 9223372036854775807로 최대가 나오며, 정수를 사용할 때 충분한 숫자를 절약하지 않으므로 필요한 것에 대해 충분히 정확하지 않습니다.

어쨌든이 주위에 있습니까?

도움이 되었습니까?

해결책

당신은 사용할 수 있습니다 BigInteger 정수 수업 및 BigDecimal 소수점 숫자가있는 숫자의 경우. 두 클래스 모두 정의됩니다 java.math 패키지.

예시:

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

다른 팁

사용 BigInteger Java 라이브러리의 일부인 클래스.

http://java.sun.com/j2se/1.5.0/docs/api/java/math/biginteger.html

다음은 큰 숫자를 매우 빨리 얻는 예입니다.

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;
    }
}

점검 BigDecimal 그리고 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));
    }
}

당신이하고있는 일에 따라 고성능 다중 예비 라이브러리 인 GMP (gmplib.org)를 살펴보고 싶을 것입니다. Java로 사용하려면 바이너리 라이브러리 주위에 JNI 포장지가 필요합니다.

BigInteger 대신에 PI를 임의의 수의 숫자로 계산하는 예를 들어 Alioth Shootout 코드 중 일부를 참조하십시오.

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

문자열 데이터 유형을 사용하면이 문제를 쉽게 해결할 수 있습니다.

class Account{
      String acc_no;
      String name;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top