Get Prime Numbers with BigInteger in Java



In this article, we will learn how to generate prime numbers using the BigInteger class in Java. A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. Here, we have the BigInteger type, which has operations for modular arithmetic, GCD calculation, primality testing, prime generation, etc.

Steps to get the prime numbers with BigInteger type

Following are the steps to get the prime numbers with BigInteger type ?

  • First, we will import the BigInteger from the java.math package.
  • Initialize the Demo class and start with a variable to count from 0.
  • We will use a While Loop to continuously check for prime numbers until a specified limit is reached (in this case, 50).
  • We will check the conditions:
    • Skip numbers less than or equal to 1, as they are not prime.
    • Use the isProbablePrime() method of BigInteger to check if the current number is prime.
  • Print each prime number found.

Java program to get the prime numbers with BigInteger type

Below is the Java program to get the prime numbers with BigInteger type ?

import java.math.BigInteger;
public class Demo {
   public static void main(String[] args) {
      int val = 0;
      System.out.println("Prime Numbers...");
      while (true) {
         if (val > 50) {
            break;
         }
         if (val > 1) {
            if (new BigInteger(val+"").isProbablePrime(val / 2)) {
               System.out.println(val);
            }
         }
         val++;
      }
   }
}

Output

Prime Numbers...
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47

Code explanation

In the program, we start by initializing a variable val to 0 and then enter a while loop that continues indefinitely. We set a condition to break out of the loop once the val exceeds 50. Inside the loop, we first check if the val is greater than 1 to exclude non-prime candidates. For each valid val, we create a new BigInteger object and use the isProbablePrime() method to determine if it is a prime number, based on the given certainty (in this case, half of val). If it is a prime, we print it to the console.

Updated on: 2024-11-04T18:44:41+05:30

550 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements