Question:

How Java compare two big integers?

by  |  earlier

0 LIKES UnLike

I try use java program to compare two big integers such as

long a = 432709;

long b = 8590367301; (too big)

if ((b - a) == 0) System.out.println("They are the same.");

else System.out.println("They are different.");

The result is "They are the same." or compile fail. How can I fix this?

 Tags:

   Report

2 ANSWERS


  1. That wouldn't work, because long b = 8590367301... and Java only supports up to 2bn.


  2. You can use the java.math.BigInteger class. It allows you to use numbers of arbitrary length.

    BigInteger a = new BigInteger("432709");

            BigInteger b = new BigInteger("8590367301");

            

            switch(a.compareTo(b))

            {            

                case -1: System.out.println(a + " is less than " + b); break;

                case 0:  System.out.println(a + " is equal to " + b); break;

                case 1:  System.out.println(a +  " is greater than " + b); break;

            }

Question Stats

Latest activity: earlier.
This question has 2 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.