Java Primality Test

A prime number is a natural number greater than  whose only positive divisors are  and itself. For example, the first six prime numbers are , and .

Given a large integer, , use the Java BigInteger class' isProbablePrime method to determine and print whether it's prime or not prime.

Input Format

A single line containing an integer,  (the number to be checked).

Constraints

  •  contains at most  digits.

Output Format

If  is a prime number, print prime; otherwise, print not prime.

Sample Input

13

Sample Output

prime

Explanation

The only positive divisors of  are  and , so we print prime.

SOLUTION:

import java.util.Scanner;
import java.math.BigInteger;

/*
I use isProbablePrime() with certainty = 10 to achieve 99.9% accuracy. 
However, even certainty = 1 (which achieves 50% accuracy) is enough to 
pass the HackerRank test cases.
isProbablePrime() is always 100% certain if it tells you if a number 
is "not prime". If it says "prime", it's only 99.9% certain. It may be 
the case that it just hasn't found a prime number number that divides 
the BigInteger yet.
*/
public class Solution {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        BigInteger n = scan.nextBigInteger();
        scan.close();
        System.out.println(n.isProbablePrime(10) ? "prime" : "not prime");
    }
}

 

Comments

Popular posts from this blog

Valid Username Regular Expression

Java SHA-256

Java Interface