2015-06-20 20 views
5

Biorąc pod uwagę następujące dane wejściowe:Jak przypisać bardzo dużą liczbę do BigInteger?

4534534534564657652349234230947234723947234234823048230957349573209483057 
1232400

próbowałem przypisać te wartości do BigInteger w następujący sposób.

public static void main(String[] args) { 

     Scanner sc = new Scanner(System.in); 
     BigInteger num1 = BigInteger.valueOf(sc.nextLong()); 
     sc.nextLine(); 
     BigInteger num2 = BigInteger.valueOf(sc.nextLong()); 

     BigInteger additionTotal = num1.add(num2); 
     BigInteger multiplyTotal = num1.multiply(num2); 

     System.out.println(additionTotal); 
     System.out.println(multiplyTotal); 
    } 

Pierwsza wartość jest poza granicami przez długi numer, a więc pojawia się następujący wyjątek:

Wyjątek w wątku „głównym” java.util.InputMismatchException: dla wejścia ciąg : "4534534534564657652349234230947234723947234234823048230957349573209483057"

Sądziłem, że BigInteger oczekuje typu long do użytku z valueOf() metody (jak stat ed here). Jak mogę przekazywać bardzo duże liczby do BigInteger?

Odpowiedz

2

Czytaj ogromną liczbę w postaci ciągu znaków.

public static void main(String[] args) 
{ 
    Scanner in = new Scanner(System.in); 
    String s = in.nextLine(); 
    BigInteger num1 = new BigInteger(s); 

    s = in.nextLine(); 
    BigInteger num2 = new BigInteger(s); 

    //do stuff with num1 and num2 here 
} 
Powiązane problemy