简体   繁体   中英

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).

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)

you can do it in a more mathematical way and not only check until prime factor 7. Here is my solution:

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. 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

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

// 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:

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; this means that you'll start getting the wrong answer for n >= 121 .

Just because everybody else has basically proposed the same algorithm, here's another one which is simple to implement: Sieve of 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 ).

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