Hackerrank Java Primality Test Solution
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 in java8
Approach 1.
import java.util.Scanner;
public class Solution
{
public static void main(String[] args)
{
try (Scanner scanner = new Scanner(System.in);)
{
System.out.println(scanner.nextBigInteger().isProbablePrime(100) ? "prime" : "not prime");
}
}
}
Approach 2.
import java.util.Scanner;
import java.math.BigInteger;
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");
}
}
Approach 3.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
BigInteger n = in.nextBigInteger();
in.close();
// Write your code here.
boolean b=n.isProbablePrime(1);
if(b){System.out.print("prime");}else{System.out.print("not prime");}
}
}