Prime number checker using Java

后端 未结 1 842
忘了有多久
忘了有多久 2021-01-22 17:59

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

相关标签:
1条回答
  • 2021-01-22 18:13

    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 BigIntegers. 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 BigIntegers. For huge floats there is BigDecimal class. Let's focus on BigIntegers.

    BigInteger

    BigInteger class has three public static fields of BigIntegers: 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 BigIntegers 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.

    0 讨论(0)
提交回复
热议问题