
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Generate Random BigInteger Value in Java
To generate random BigInteger in Java, let us first set a min and max value −
BigInteger maxLimit = new BigInteger("5000000000000"); BigInteger minLimit = new BigInteger("25000000000");
Now, subtract the min and max −
BigInteger bigInteger = maxLimit.subtract(minLimit); Declare a Random object and find the length of the maxLimit: Random randNum = new Random(); int len = maxLimit.bitLength();
Now, set a new B integer with the length and the random object created above.
Example
import java.math.BigInteger; import java.util.Random; public class Demo { public static void main(String[] args) { BigInteger maxLimit = new BigInteger("5000000000000"); BigInteger minLimit = new BigInteger("25000000000"); BigInteger bigInteger = maxLimit.subtract(minLimit); Random randNum = new Random(); int len = maxLimit.bitLength(); BigInteger res = new BigInteger(len, randNum); if (res.compareTo(minLimit) < 0) res = res.add(minLimit); if (res.compareTo(bigInteger) >= 0) res = res.mod(bigInteger).add(minLimit); System.out.println("The random BigInteger = "+res); } }
Output
The random BigInteger = 3874699348568
Advertisements