I am just a beginner in Java. I have tried to build a prime number checker using what I already know. I have used a method that finds the square root of the given number and the
Your problem is int overflow
. 2147483647
is the maximum value for int
. This data type can't store larger numbers.
Double should be used for floating numbers.
For using big integers use BigInteger
class which is java.math
class. This class can store infinitely large numbers as long as you have enough memory on your machine.
EDIT:
As You are interested in understanding how BigInteger
works I decided to edit my answer and introduce you to the world of BigInteger
s. First of all let my assure: do You understand, that double
isn't type for larger integers? In case it would be enough you can use long
which is the type for integers larger than int
.
In case long
isn't big enough you should try BigInteger
s. For huge float
s there is BigDecimal
class. Let's focus on BigInteger
s.
BigInteger
BigInteger
class has three public static
fields of BigInteger
s: ONE
, TEN
and ZERO
. In case you want to check if a BigInteger
equals 0 (yes, BigInteger
can also contain small integers) it's definitely better to compare it to BigInteger.ZERO
than creating new object BigInteger(0)
.
Construction
What about constructors? There are three most commonly used. The first one takes String
as a parameter, the second takes a String
and an int
radix (base of numeric system) and the third one takes bit array.
The last way that I use to construct BigIntegers
is a public static
method called valueOf()
which takes long
or int
as a parameter.
BigInteger a = new BigInteger("1024"); // creates BigInteger representing number 1024.
BigInteger b = new BigInteger(1024); //also creates BigInteger representing number 1024.
BigInteger c = new BigInteger("10000000000", 2); //also creates BigInteger representing 1024
Operations
To check if BigInteger a
equals BigInteger b
just type
if (a.equals(b)) {...}
To add two BigInteger
s a,b
type
BigInteger c = a.add(b);
//or
a = a.add(b);
Feel free to read the documentation which is great! Anyway, If You have any questions feel free to ask in the comment section. I'll respond until Sunday evening.