0
public class Karatsubamultiplication {

    public static void multiply(long ac , long ad, long bc, long bd, long digits)
    
    {
      double mul=0;
      
      mul = Math.pow(10, digits) *ac + Math.pow(10, digits/2)*(ad+bc)+bd;
      
      System.out.println("The multiplication answer is "+mul);
    }
    
    public static long[] splitnum(long n1) {
        long[] split= new long[3];
        long divider=1;
        long num =0;
        long counter=0;
        num=n1;
        while(num>0) {
            num=num/10;
            counter=counter+1;
        }
        split[2]=counter;
        for(long i=0;i<counter/2;i++) {
            divider*=10;
        }       
        split[0]=n1/divider;
        split[1]=n1%divider;
                
        return split;       
    }
    
    public static void main(String[] args) {
            
        Scanner sc = new Scanner(System.in);    
        System.out.println("Enter value of n1 and n2 ");
        long n1 = sc.nextLong();
        long n2 = sc.nextLong();
        long ac=0,ad=0,bc=0,bd=0,digits=0;
        if(n1/10==0 && n2/10==0)
        {
            System.out.println("The multiplication answer is "+n1*n2);
        }
        else
        {
            long[] a= splitnum(n1);
            long[] c =splitnum(n2);     
            ac = a[0]*c[0];
            ad = a[0]*c[1];
            bc= a[1]*c[0];
            bd= a[1]*c[1];
            digits=a[2];
            multiply(ac,ad,bc,bd,digits);
            
        }
                                
    }       
}

Multiplication of two 64 digit number_Gettin Input Mismatch Exception

Query : when i give 2 64 bit number result will be in 128 bits. Getting Input Mismatch exception:(

Need help to enhance this code in order to handle this exception .>

Siva
  • 17
  • 7

1 Answers1

1

InputMismatchException is thrown by the nextLong() method, when the input entered by the user is not, in fact, a long.

The way you've used scanner means that nextLong is looking for a space, enter (newline), end of the stream, or other whitespace, and will then parse all the character that precede it as a long. Note that this means the input must consist of an optional + or -, and then a bunch of digits, and that is all, and that the number must fit between -2^63 and +2^63-1 (so, between -9223372036854775808 and +9223372036854775807). Any number below/above that isn't a long and therefore causes that exception.

Fix: Well, you tell me. What do you want this program to do? Any numbers outside of that range do not fit into the long datatype in the first place.

If you don't need your program to deal with numbers that extreme, then.. don't enter them.

If you do, then this code needs to be replaced entirely; don't call .nextLong() at all. Presumably, just call .next() and use java.math.BigInteger instead of longs, which can take numbers of any size.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72