- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to get the prime numbers with BigInteger type
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
Advertisements