简体   繁体   English

用户输入的Java素数检查

[英]Java Prime Number check with User Input

I just started coding for college and I had to write a program that checks user inputs (integers) if they're a prime number or not. 我刚刚开始为大学编程,我不得不编写一个程序来检查用户输入(整数)是否为质数。

I've been getting good results but I wanted to ask for your opinion and whether I forgot something. 我一直都取得不错的成绩,但我想征求您的意见以及我是否忘记了一些东西。

package uebung_3;


import java.util.Scanner;

public class PrimZahlen {

    public static void main(String[] args) {

        System.out.print("Enter a number: ");
        Scanner key = new Scanner(System.in);
        int in = key.nextInt();

        prim(in);
    }

    private static void prim(int in) {//int in is a Scanner var.
        if (in == 2 || in == 3) {

            System.out.println(in + " is a prime number");
        } else if (in == 5 || in == 7) {
            System.out.println(in + " is a prime number");
        } else if (in % 2 == 0 || in % 3 == 0) {
            System.out.println(in + " is not a prime number.");
        } else if (in % 5 == 0 || in % 7 == 0) {
            System.out.println(in + " is not a prime number.");
        } else {
            System.out.println(in + " is a prime number.");
        }
    }

}

You shold check that number has only 2 devisors (1 and himself). 您要检查该数字是否只有2个除数(1个和他本人)。

For example: 例如:

static boolean isPrime(int n) {
    for (int i = 2; i < n; i++) {
        if (n % i == 0)
            return false;
    }
    return true;
}

Range for iteration can be optimized (from 2 to i^2<=n) 迭代范围可以优化(从2到i ^ 2 <= n)

you can do it in a more mathematical way and not only check until prime factor 7. Here is my solution: 您可以用更数学的方式做到这一点,不仅要检查素数7。这是我的解决方案:

public static void main(final String[] args) {
    System.out.print("Enter a number: ");
    final Scanner key = new Scanner(System.in);
    final int in = key.nextInt();

    if (isPrime(in)) {
        System.out.println(in + " is a prime number");
    } else {
        System.out.println(in + " is not a prime number");
    }
}

private static boolean isPrime(final int in) {
    if (in < 2) return false;

    for (int i=2; i <= Math.sqrt(in); i++){
        if (in%i == 0){
            return false;
        }
    }
    return true;
}

Prime numbers have only 2 divisors the 1 and the number itself. 质数只有2除数1和数字本身。 So to check whether a number is prime or not you have to check all the possible divisors of that number. 因此,要检查数字是否为质数,必须检查该数字的所有可能的除数。 For example: 例如:

boolean isPrimeNumber(int num){
    if(num < 2)
        return false;
    for(int i = 2; i <= Math.sqrt(num); i++){
        if(num % i == 0){
            return false;
        }
    }
    return true;
}

The wikipedia entry on primality test gives a better algorithm for testing than presented so far and we can implement it in Java trivially enough like 关于素性测试的Wikipedia条目提供了比到目前为止提供的更好的测试算法,我们可以像使用Java一样轻松地实现它

private static boolean isPrime(int n) {
    if (n <= 1) {
        return false;
    } else if (n <= 3) {
        return true;
    } else if (n % 2 == 0 || n % 3 == 0) {
        return false;
    }
    int sq = (int) Math.ceil(Math.sqrt(n));
    for (int i = 5; i <= sq; i += 6) {
        if (n % i == 0 || n % 2 + i == 0) {
            return false;
        }
    }
    return true;
}

And change your main method to use it, something like 并更改您的main使用方式,例如

// prim(in);
if (isPrime(in)) {
    System.out.printf("%d is prime.%n", in);
} else {
    System.out.printf("%d is not prime.%n", in);
}

Your program is incorrect. 您的程序不正确。 This is right implementation which now check all integer numbers from minus infinity to infinity considering 1 as non-prime number: 这是正确的实现,现在检查从负无穷大到无穷大的所有整数,并将1作为非质数:

public boolean isPrime(int number) {
        if(number < 2) return false;
        for(int i = 2; i <= Math.sqrt(number); i++) {
            if(n % i == 0) {
                return false;
            }
        }
        return true;
    }

The biggest problem is that you're not checking prime factors greater than 7; 最大的问题是,您没有检查大于7的素数。 this means that you'll start getting the wrong answer for n >= 121 . 这意味着对于n >= 121 ,您将开始得到错误的答案。

Just because everybody else has basically proposed the same algorithm, here's another one which is simple to implement: Sieve of Eratosthenes : 仅仅因为其他人基本上都提出了相同的算法,所以这是另一个易于实现的算法: Eratosthenes筛

boolean isPrime(int n) {
  if (n <= 0) return false;

  // sieve is basically a boolean[], where each element will
  // contain "true" if the number is prime, "false" otherwise.
  BitSet sieve = new BitSet(n + 1);
  sieve.set(0, n + 1);

  // Zero isn't prime, nor is 1.
  sieve.clear(0); sieve.clear(1);

  for (int i = 2; i <= n; ++i) {
    if (sieve.get(i)) {
      // i is a prime number.
      // Mark all multiples of i as non-prime.
      for (int j = 2 * i; j <= n; j += i) {
        sieve.clear(j);
      }
    }
  }

  // n is prime if the corresponding element in the sieve is "true".
  return sieve.get(n);
}

Note that you can factor this in such a way that you can reuse the sieve BitSet for multiple calls to the method (specifically, you can use it again for a smaller value of n ). 请注意,您可以采用这种方式进行BitSet ,以便将sieve BitSet重复用于该方法的多次调用(具体来说,您可以再次将其用于较小的n )。

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

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