Java Program to Implement Inversion Method for Random Number Generation
Last Updated :
23 Jun, 2021
Here we will be going through the inversion method for random number generation in java. So basically we will be illustrating two approaches which are as follows:
- Shuffling elements in an array
- Using Collection.shuffle() method
Important Method here namely is setSeed(). It is used to set the seed via setSeed() method of Random class sets of the random number generator using a single long seed.
Syntax:
setSeed()
Example 1:
Java
// Java Program to implement inversion for random number
// generation
// Importing Random class from java.util package
import java.util.Random;
// Main class
class GFG {
// Method 1
// To calculate seed value
public static long calcSeed(long nextLong)
{
// Declaring and initializing variables
// Custom initialization
final long x = 0x5DEECE66DL;
final long xinv = 0xdfe05bcb1365L;
final long y = 0xBL;
final long mask = ((1L << 48) - 1);
long a = nextLong >>> 32;
long b = nextLong & ((1L << 32) - 1);
if ((b & 0x80000000) != 0)
a++;
// b had a sign bit, so we need to restore a
long q = ((b << 16) - y - (a << 16) * x) & mask;
for (long k = 0; k <= 5; k++) {
long rem = (x - (q + (k << 48))) % x;
long d = (rem + x) % x; // force positive
if (d < 65536) {
long c = ((q + d) * xinv) & mask;
if (c < 65536) {
return ((((a << 16) + c) - y) * xinv)
& mask;
}
}
}
// Throws keyword pops up the message
// as exception is encountered during runtime
throw new RuntimeException("Failed!!");
}
// Method 2
// Main driver method
public static void main(String[] args)
{
// Setting a random number in main() method by
// creating an object of Random class
Random r = new Random();
// Getting the next random number
long next = r.nextLong();
// Print and display the next long value
System.out.println("Next long value: " + next);
// Calling method 1
long seed = calcSeed(next);
// Print and display the ssed value
System.out.println("Seed " + seed);
// setSeed mangles the input,
// so demangling here to get the right output by
// creating another object of Random class
Random r2 = new Random((seed ^ 0x5DEECE66DL)
& ((1L << 48) - 1));
// Printing the next ssed value
// using nextLong() method
System.out.println("Next long value from seed: "
+ r2.nextLong());
}
}
OutputNext long value: 3738641717178320652
Seed 158514749661962
Next long value from seed: 3738641717178320652
Output explanation:
Random uses a 48-bit seed and a linear congruential generator. These are not cryptographically safe generators, because of the tiny state size and the fact that the output just isn't that random (many generators will exhibit small cycle length in certain bits, meaning that those bits can be easily predicted even if the other bits seem random).
Random's seed update is as follows:
nextseed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)
This is a very simple function, and it can be inverted if you know all the bits of the seed by calculating
seed = ((nextseed - 0xBL) * 0xdfe05bcb1365L) & ((1L << 48) - 1)
Since 0x5DEECE66DL * 0xdfe05bcb1365L = 1 mod 248. With this, a single seed value at any point in time suffices to recover all past and future seeds.
Random has no functions that reveal the whole seed, though, so we'll have to be a bit clever.
Now, obviously, with a 48-bit seed, you have to observe at least 48 bits of output or you clearly don't have an injective (and thus invertible) function to work with. We're in luck: nextLong returns ((long)(next(32)) << 32) + next(32);, so it produces 64 bits of output (more than we need). Indeed, we could probably make do with nextDouble (which produces 53 bits), or just repeated calls of any other function. Note that these functions cannot output more than 248 unique values because of the seed's limited size (hence, for example, there are 264-248 longs that nextLong will never produce).
Let's specifically look at nextLong. It returns a number (a << 32) + b where a and b are both 32-bit quantities. Let s be the seed before nextLong is called. Then, let t = s * 0x5DEECE66DL + 0xBL, so that a is the high 32 bits of t, and let u = t * 0x5DEECE66DL + 0xBL so that b is the high 32 bits of u. Let c and d be the low 16 bits of t and u respectively.
Note that since c and d are 16-bit quantities, we can just brute-force them (since we only need one) and be done with it. That's pretty cheap since 216 is only 65536 -- tiny for a computer. But let's be a bit more clever and see if there's a faster way.
We have (b << 16) + d = ((a << 16) + c) * 0x5DEECE66DL + 11. Thus, doing some algebra, we obtain (b << 16) - 11 - (a << 16)*0x5DEECE66DL = c*0x5DEECE66DL - d, mod 248. Since c and d are both 16-bit quantities, c*0x5DEECE66DL has at most 51 bits. This usefully means that
(b << 16) - 11 - (a << 16)*0x5DEECE66DL + (k<<48)
is equal to c*0x5DEECE66DL - d for some k at most 6. (There are more sophisticated ways to compute c and d, but because the bound on k is so tiny, it's easier to just brute force).
We can just test all the possible values for k until we get a value whose negated remainder mod 0x5DEECE66DL is 16 bits (mod 248 again), so that we recover the lower 16 bits of both t and u. At that point, we have a full seed, so we can either find future seeds using the first equation, or past seeds using the second equation. It is as shown in the example given below which is as follows:
Example 2:
Java
// Java Program to Implement Inversion Method for
// Random Number Generation
// Importing required classes
import java.util.Arrays;
import java.util.Random;
import javax.sql.RowSetEvent;
import javax.sql.RowSetListener;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetProvider;
// Main class
// To test random reverse
class GFG {
// The secret seed that we want to find
private static long SEED = 782634283105L;
// Number of random numbers to be generated
private static int NUM_GEN = 5;
// Method 1
private static int[] genNum(long seed)
{
Random rand = new Random(seed);
int arr[] = new int[NUM_GEN];
for (int i = 0; i < arr.length; i++) {
arr[i] = rand.nextInt();
}
return arr;
}
// Method 2
// Main driver method
public static void main(String args[])
{
int arr[] = genNum(SEED);
System.out.println(Arrays.toString(arr));
Long result = reverse(arr);
if (result != null) {
System.out.println(
Arrays.toString(genNum(result)));
}
else {
System.out.println("Seed not found");
}
}
// Method 3
private static long combine(int rand, int suffix)
{
return (unsignedIntToLong(rand) << 16)
| (suffix & ((1L << 16) - 1));
}
// Method 4
private static long unsignedIntToLong(int num)
{
return num & ((1L << 32) - 1);
}
// Method 5
// To find the seed of a sequence of
// integer, generated by nextInt() Can be easily
// modified to find the seed of a sequence of long,
// generated by nextLong()
private static Long reverse(int arr[])
{
// Need at least 2 numbers.
assert (arr.length > 1);
int end = arr.length - 1;
// Brute force lower 16 bits, then compare
// upper 32 bit of the previous seed generated
// to the previous number.
for (int i = 0; i < (1 << 16); i++) {
long candidateSeed = combine(arr[end], i);
long previousSeed
= getPreviousSeed(candidateSeed);
if ((previousSeed >>> 16)
== unsignedIntToLong(arr[end - 1])) {
System.out.println("Testing seed: "
+ previousSeed + " --> "
+ candidateSeed);
for (int j = end - 1; j >= 0; j--) {
candidateSeed = previousSeed;
previousSeed
= getPreviousSeed(candidateSeed);
if (j > 0
&& (previousSeed >>> 16)
== unsignedIntToLong(
arr[j - 1])) {
System.out.println(
"Verifying: " + previousSeed
+ " --> " + candidateSeed);
}
else if (j == 0) {
// The XOR is done when the seed is
// set, need to reverse it
System.out.println(
"Seed found: "
+ (previousSeed ^ MULTIPLIER));
return previousSeed ^ MULTIPLIER;
}
else {
// Print statement
System.out.println("Failed");
// break keyword
break;
}
}
}
}
return null;
}
private static long ADDEND = 0xBL;
private static long MULTIPLIER = 0x5DEECE66DL;
// Method 6
private static long getPreviousSeed(long currentSeed)
{
long seed = currentSeed;
// Reverse the addend from the seed
// Reversing the addend
seed -= ADDEND;
long result = 0;
// Iterating through the seeds bits
for (int i = 0; i < 48; i++) {
long mask = 1L << i;
// find the next bit
long bit = seed & mask;
// add it to the result
result |= bit;
if (bit == mask) {
// if the bit was 1, subtract its effects
// from the seed
seed -= MULTIPLIER << i;
}
}
return result & ((1L << 48) - 1);
}
}
Output:
[826100673, 702667566, 238146028, -1525439028, -133372456]
Testing seed: 181503804585936 --> 272734279476123
Verifying: 15607138131897 --> 181503804585936
Verifying: 46050021665190 --> 15607138131897
Verifying: 54139333749543 --> 46050021665190
Seed found: 782634283105
[826100673, 702667566, 238146028, -1525439028, -133372456]
Output explanation: The program will brute force on the lower 16
- -bit discarded by nextInt(), use the algorithm provided in the blog by James Roper to find the previous seed, then check that the upper 32 bit of the 48-bit seed is the same as the previous number. We need at least 2 integers to derive the previous seed. Otherwise, there will be 216 possibilities for the previous seed, and all of them are equally valid until we have at least one more number.
- It can be extended for nextLong() easily, and 1 long number is enough to find the seed, since we have 2 pieces of upper 32-bit of the seed in one long, due to the way it is generated.
Note: There are cases where the result is not the same as what you set as secret seed in the SEED variable. If the number you set as secret seed occupies more than 48-bit (which is the number of bits used for generating random numbers internally), then the upper 16 bits of 64 bit of long will be removed in the setSeed() method. In such cases, the result returned will not be the same as what you have set initially, it is likely that the lower 48-bit will be the same.
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. Known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Syntax and s
7 min read
Basics
Introduction to JavaJava is a high-level, object-oriented programming language developed by Sun Microsystems in 1995. It is mostly used for building desktop applications, web applications, Android apps, and enterprise systems.Key Features of JavaPlatform Independent: Java is famous for its Write Once, Run Anywhere (WOR
4 min read
Java Programming BasicsJava is a class-based, object-oriented programming language that is designed to be secure and portable. Its core principle is âWrite Once, Run Anywhereâ (WORA), meaning Java code can run on any device or operating system that has a Java Virtual Machine (JVM).Java Development Environment: To run Java
9 min read
Java MethodsJava Methods are blocks of code that perform a specific task. A method allows us to reuse code, improving both efficiency and organization. All methods in Java must belong to a class. Methods are similar to functions and expose the behavior of objects.Example: Java program to demonstrate how to crea
7 min read
Access Modifiers in JavaIn Java, access modifiers are essential tools that define how the members of a class, like variables, methods, and even the class itself, can be accessed from other parts of our program. They are an important part of building secure and modular code when designing large applications. In this article
6 min read
Arrays in JavaIn Java, an array is an important linear data structure that allows us to store multiple values of the same type. Arrays in Java are objects, like all other objects in Java, arrays implicitly inherit from the java.lang.Object class. This allows you to invoke methods defined in Object (such as toStri
9 min read
Java StringsIn Java, a String is the type of object that can store a sequence of characters enclosed by double quotes and every character is stored in 16 bits, i.e., using UTF 16-bit encoding. A string acts the same as an array of characters. Java provides a robust and flexible API for handling strings, allowin
8 min read
Regular Expressions in JavaIn Java, Regular Expressions or Regex (in short) in Java is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are a few areas of strings where Regex is widely used to define the constraints. Regular Expressi
7 min read
OOPs & Interfaces
Classes and Objects in JavaIn Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. A class is a template to create objects having similar properties and behavior, or in other words, we can say that a class is a blueprint for objects.An
10 min read
Java ConstructorsIn Java, constructors play an important role in object creation. A constructor is a special block of code that is called when an object is created. Its main job is to initialize the object, to set up its internal state, or to assign default values to its attributes. This process happens automaticall
10 min read
Java OOP(Object Oriented Programming) ConceptsBefore Object-Oriented Programming (OOPs), most programs used a procedural approach, where the focus was on writing step-by-step functions. This made it harder to manage and reuse code in large applications.To overcome these limitations, Object-Oriented Programming was introduced. Java is built arou
10 min read
Java PackagesPackages in Java are a mechanism that encapsulates a group of classes, sub-packages and interfaces. Packages are used for: Prevent naming conflicts by allowing classes with the same name to exist in different packages, like college.staff.cse.Employee and college.staff.ee.Employee.Make it easier to o
7 min read
Java InterfaceAn Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
11 min read
Collections
Exception Handling
Java Exception HandlingException handling in Java is an effective mechanism for managing runtime errors to ensure the application's regular flow is maintained. Some Common examples of exceptions include ClassNotFoundException, IOException, SQLException, RemoteException, etc. By handling these exceptions, Java enables deve
8 min read
Java Try Catch BlockA try-catch block in Java is a mechanism to handle exceptions. This make sure that the application continues to run even if an error occurs. The code inside the try block is executed, and if any exception occurs, it is then caught by the catch block.Example: Here, we are going to handle the Arithmet
4 min read
Java final, finally and finalizeIn Java, the keywords "final", "finally" and "finalize" have distinct roles. final enforces immutability and prevents changes to variables, methods or classes. finally ensures a block of code runs after a try-catch, regardless of exceptions. finalize is a method used for cleanup before an object is
4 min read
Chained Exceptions in JavaChained Exceptions in Java allow associating one exception with another, i.e. one exception describes the cause of another exception. For example, consider a situation in which a method throws an ArithmeticException because of an attempt to divide by zero.But the root cause of the error was an I/O f
3 min read
Null Pointer Exception in JavaA NullPointerException in Java is a RuntimeException. It occurs when a program attempts to use an object reference that has the null value. In Java, "null" is a special value that can be assigned to object references to indicate the absence of a value.Reasons for Null Pointer ExceptionA NullPointerE
5 min read
Exception Handling with Method Overriding in JavaException handling with method overriding in Java refers to the rules and behavior that apply when a subclass overrides a method from its superclass and both methods involve exceptions. It ensures that the overridden method in the subclass does not declare broader or new checked exceptions than thos
4 min read
Java Advanced
Java Multithreading TutorialThreads are the backbone of multithreading. We are living in the real world which in itself is caught on the web surrounded by lots of applications. With the advancement in technologies, we cannot achieve the speed required to run them simultaneously unless we introduce the concept of multi-tasking
15+ min read
Synchronization in JavaIn multithreading, synchronization is important to make sure multiple threads safely work on shared resources. Without synchronization, data can become inconsistent or corrupted if multiple threads access and modify shared variables at the same time. In Java, it is a mechanism that ensures that only
10 min read
File Handling in JavaIn Java, with the help of File Class, we can work with files. This File Class is inside the java.io package. The File class can be used to create an object of the class and then specifying the name of the file.Why File Handling is Required?File Handling is an integral part of any programming languag
6 min read
Java Method ReferencesIn Java, a method is a collection of statements that perform some specific task and return the result to the caller. A method reference is the shorthand syntax for a lambda expression that contains just one method call. In general, one does not have to pass arguments to method references.Why Use Met
9 min read
Java 8 Stream TutorialJava 8 introduces Stream, which is a new abstract layer, and some new additional packages in Java 8 called java.util.stream. A Stream is a sequence of components that can be processed sequentially. These packages include classes, interfaces, and enum to allow functional-style operations on the eleme
15+ min read
Java NetworkingWhen computing devices such as laptops, desktops, servers, smartphones, and tablets and an eternally-expanding arrangement of IoT gadgets such as cameras, door locks, doorbells, refrigerators, audio/visual systems, thermostats, and various sensors are sharing information and data with each other is
15+ min read
JDBC TutorialJDBC stands for Java Database Connectivity. JDBC is a Java API or tool used in Java applications to interact with the database. It is a specification from Sun Microsystems that provides APIs for Java applications to communicate with different databases. Interfaces and Classes for JDBC API comes unde
12 min read
Java Memory ManagementJava memory management is the process by which the Java Virtual Machine (JVM) automatically handles the allocation and deallocation of memory. It uses a garbage collector to reclaim memory by removing unused objects, eliminating the need for manual memory managementJVM Memory StructureJVM defines va
4 min read
Garbage Collection in JavaGarbage collection in Java is an automatic memory management process that helps Java programs run efficiently. Objects are created on the heap area. Eventually, some objects will no longer be needed.Garbage collection is an automatic process that removes unused objects from heap.Working of Garbage C
6 min read
Memory Leaks in JavaIn programming, a memory leak happens when a program keeps using memory but does not give it back when it's done. It simply means the program slowly uses more and more memory, which can make things slow and even stop working. Working of Memory Management in JavaJava has automatic garbage collection,
3 min read
Practice Java
Java Interview Questions and AnswersJava is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java Programs - Java Programming ExamplesIn this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Java Exercises - Basic to Advanced Java Practice Programs with SolutionsLooking for Java exercises to test your Java skills, then explore our topic-wise Java practice exercises? Here you will get 25 plus practice problems that help to upscale your Java skills. As we know Java is one of the most popular languages because of its robust and secure nature. But, programmers
7 min read
Java Quiz | Level Up Your Java SkillsThe best way to scale up your coding skills is by practicing the exercise. And if you are a Java programmer looking to test your Java skills and knowledge? Then, this Java quiz is designed to challenge your understanding of Java programming concepts and assess your excellence in the language. In thi
1 min read
Top 50 Java Project Ideas For Beginners and Advanced [Update 2025]Java is one of the most popular and versatile programming languages, known for its reliability, security, and platform independence. Developed by James Gosling in 1982, Java is widely used across industries like big data, mobile development, finance, and e-commerce.Building Java projects is an excel
15+ min read