Skip to content
the poor coder

Hackerrank Java Primality Test Solution

Poor Man
Published
Updated
Reading time
1 min read

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

Text
13

Sample Output

Text
prime

Explanation

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

Solution in java8#

Approach 1.

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

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

Python
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");}
   }
}

Keep going

2020

Hackerrank Java BigInteger Solution

In this problem, you have to add and multiply huge numbers! These numbers are so big that you can't contain them in any ordinary data types like a long integer. Use the power of Java's BigInteger class and solve this…

2020

Hackerrank Java BigDecimal Solution

Java's BigDecimal class can handle arbitrary-precision signed decimal numbers. Let's test your knowledge of them! Given an array, , of real number strings, sort them in descending order — but wait, there's more! Each…

ESC