简体   繁体   English

使用Java的素数检查器

[英]Prime number checker using Java

I am just a beginner in Java. 我只是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; 我使用一种方法来找到给定数字的平方根,然后将数字除以小于该根的所有整数,如果在任何情况下答案为“ 0”,则该数字不是质数; 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". 我的程序在整数数据类型(最大编号为2147483647)下运行良好,但是在每个数字之后都给出相同的输出,例如->“是!数字是质数”。 Because of this I've tried using double data type but the result is still the same! 因此,我尝试使用double数据类型,但结果仍然相同! For every number after 2147483647 it says it is a prime number. 对于2147483647之后的每个数字,它表示是质数。


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 问题 :使用Math.floor()double存储更大的舍入数后,当我打印ArrayList它在其中显示元素“ 0”,但最终结果条件if (contains(0) == true )为绕过并且为大于2147483647的数字实现if ( contains (0) == false )


First Code using the Integer data type: 使用Integer数据类型的第一个代码:

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 : 第二个代码使用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 . 您的问题是int overflow 2147483647 is the maximum value for int . 2147483647int的最大值。 This data type can't store larger numbers. 此数据类型不能存储更大的数字。

Double should be used for floating numbers. Double应该用于浮点数。

For using big integers use BigInteger class which is java.math class. 要使用大整数,请使用BigInteger类,它是java.math类。 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. 当您有兴趣了解BigInteger工作原理时,我决定编辑答案,并向您介绍BigInteger的世界。 First of all let my assure: do You understand, that double isn't type for larger integers? 首先让我保证:您了解吗,不是为大整数键入double吗? In case it would be enough you can use long which is the type for integers larger than int . 万一足够,您可以使用long ,它是大于int整数的类型。

In case long isn't big enough you should try BigInteger s. 如果long不够long ,则应尝试使用BigInteger For huge float s there is BigDecimal class. 对于巨大的floatBigDecimal类。 Let's focus on BigInteger s. 让我们专注于BigInteger

BigInteger 的BigInteger

BigInteger class has three public static fields of BigInteger s: ONE , TEN and ZERO . BigInteger类有三个public static字段BigInteger S: ONETENZERO 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) . 如果要检查BigInteger等于0(是的, BigInteger也可以包含小整数),则将其与BigInteger.ZERO进行比较肯定比创建新对象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. 第一个使用String作为参数,第二个使用String和一个int基数(数字系统的基数),第三个使用位数组。

The last way that I use to construct BigIntegers is a public static method called valueOf() which takes long or int as a parameter. 我用来构造BigIntegers的最后一种方法是一个称为valueOf()public static方法,该方法需要longint作为参数。

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 要检查BigInteger a等于BigInteger b只需键入

if (a.equals(b)) {...}

To add two BigInteger s a,b type 要添加两个BigIntegera,b类型

 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. 我会回复到周日晚上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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