Hackerrank Java Primality Test Solution
1 min read

Hackerrank Java Primality Test Solution

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


  • contains at most  digits.

Output Format

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

Sample Input


Sample Output



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();
        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();
      // Write your code here.
       boolean b=n.isProbablePrime(1);
      if(b){System.out.print("prime");}else{System.out.print("not prime");}

Enjoying these posts? Subscribe for more

Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.