Subject
- #Prime Number Identification
- #Lazy Evaluation
- #Optimization
- #Stream
- #Java
Created: 2024-07-23
Created: 2024-07-23 19:39
Typically, to check if a number 'n' is prime, we divide 'n' by numbers from 2 to n - 1 and check if it is divisible.
Let's apply some optimizations to this method to improve its efficiency and utilize Stream to implement lazy evaluation.
The following is a naive method to check if 'n' is a prime number.
Java's Stream, unlike List, does not perform operations immediately when they are defined.
It waits in a state where it is defined how to calculate each element, and only performs the calculation to obtain a specific element when that element is needed.
Using this, we can create a Stream that finds prime numbers as follows.
Complete Code
Execution Result
Comments0