简体   繁体   中英

Prime number checker using Java

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 then divides the number with all the integers less than that root and if in any one case answer is "0" then the number is not a prime; otherwise, it is.


My program works well with integer data type upto no.2147483647 but after this number for each and every number it gives the same output like --> "Yes!! The number is a prime number". Because of this I've tried using double data type but the result is still the same! For every number after 2147483647 it says it is a prime number.


Question : after using Math.floor() and double to store a bigger rounded off number, when I print my ArrayList it shows element "0" in it, but the in final result condition if (contains(0) == true ) is bypassed and if ( contains (0) == false ) is implemented for numbers greater than 2147483647


First Code using the Integer data type:

import java.util.ArrayList;
import java.util.Scanner;
public class UltimatePrime {
    public static void main (String[] args)
    {
        int mod;
        Scanner input = new Scanner(System.in);
        int number = (int) input.nextDouble(); //separate and get only integer part from the input 

        if (number >= 2 && number < 2147483647) //2147483647 is the limit for data type Integer
        {
            int j = (int) Math.sqrt(number); //get the integer square root of the input and assign it to j
            ArrayList modStorage = new ArrayList();
            for (; j>1; j--)
            {
                mod = number % j;  //divide the number with all numbers less than or equal to j
                modStorage.add(mod); //store all modulus or remainder operator results in ArrayList modStorage
            }
                if (modStorage.contains(0) == true) //if ArrayList modStorage contains 0 remainder than result = true
                {
                    System.out.println("Sorry" + ", " + number + " " + "is not a prime number.");
                }
                if (modStorage.contains(0) == false) //if ArrayList modStorage doesn't contain 0 remainder than result = false
                {
                    System.out.println("Yes!!" + " " + number + " " + "is a prime number.");
                }
            }

        else if ( number == 1) //special case for number 1
        {
            System.out.println("A prime number has only two factors: 1 and itself."
                    + "\nA composite number has more than two factors."
                    + "\nThe number 1 is neither prime nor composite.");
        }

        else //insuarace :D
        {
            System.out.println("Please enter proper number!");
        }

        input.close();
    }
}

Second Code using double :

import java.util.ArrayList;
import java.util.Scanner;
public class FinalPrime {
    public static void main (String[] args)
    {
        double mod;
        Scanner input = new Scanner(System.in);
        double number = input.nextDouble(); //separate and get only integer part from the input 
        number = Math.floor(number);
        if (number >= 2) 
            {
                double j = Math.sqrt(number); //get the integer square root of the input and assign it to j
                j = Math.floor(j);
                ArrayList modStorage = new ArrayList();
                for (; j>1; j--)
                {
                    mod = number % j;  //divide the number with all numbers less than or equal to j
                    modStorage.add(mod); //store all modulus or remainder operator results in ArrayList modStorage
                }
                if (modStorage.contains(0) == true) //if ArrayList modStorage contains 0 remainder than result = true
                {
                    System.out.printf("%.0f \n",number);
                    System.out.println("Sorry" + ", " + "it is not a prime number.");
                }
                if (modStorage.contains(0) == false) //if ArrayList modStorage doesn't contain 0 remainder than result = false
                {
                    System.out.printf("%.0f \n",number);
                    System.out.println("Yes!!" + ", " + "it is a prime number.");
                }
            }

        else if ( number == 1) //special case for number 1
            {
                System.out.println("A prime number has only two factors: 1 and itself."
                                + "\nA composite number has more than two factors."
                                + "\nThe number 1 is neither prime nor composite.");
            }

        else //insuarace :D
            {
                System.out.println("Please enter proper number!");
            }

        input.close();
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM