Java Program to get the prime numbers with BigInteger type

Java 8Object Oriented ProgrammingProgramming

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.

At first, we have set the value to 0 and then considered a while loop. Since 0 and 1 aren’t prime numbers, we will be generating prime numbers after that:

int val = 0;
System.out.println("Prime Numbers...");
while (true) {
   // conditions
}

Under while, we have set the following two condition. On increment, when the value of val become greater than 1 i.e.2, it goes under the second if condition. Inside that, we have used the isProbablePrime() method to generate prime numbers:

while (true) {
   if (val > 50) {
      break;
   }
   if (val > 1) {
      if (new BigInteger(val+"").isProbablePrime(val / 2)) {
         System.out.println(val);
      }
   }
}

Example

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
raja
Published on 24-Apr-2019 12:21:22
Advertisements