- 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 display a prime number less than the given number
Let’s say the value you have set is 20 and you have to display a prime number less than this value i.e. 19 in this case.
The following is an example that displays a prime number less than the given number −
Example
public class Demo { public static void main(String[] args) { int val = 20; boolean[] isprime = new boolean[val + 1]; for (int i = 0; i<= val; i++) isprime[i] = true; // 0 and 1 is not prime isprime[0] = false; isprime[1] = false; int n = (int) Math.ceil(Math.sqrt(val)); for (int i = 0; i<= n; i++) { if (isprime[i]) for (int j = 2 * i; j<= val; j = j + i) // not prime isprime[j] = false; } int myPrime; for (myPrime = val; !isprime[myPrime]; myPrime--); // empty loop body System.out.println("Largest prime less than or equal to " + val + " = " + myPrime); } }
Output
Largest prime less than or equal to 20 = 19
Above, we have set the following as non-prime since both 0 and 1 are non-prime −
isprime[0] = false; isprime[1] = false;
Advertisements