- 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
Different Methods to find Prime Number in Java
A prime number is a number that is only divisible by one or itself. Some of the prime numbers are 2, 3, 5, 7, 11, 13 etc.
Some of the different methods to find a prime number in Java are given as follows −
Method 1 - Find if a number is prime without using a function
A program that finds if the given number is prime without using a function is given as follow −
Example
public class Example { public static void main(String args[]) { int num = 11, flag=0; if(num == 0||num == 1) { System.out.println( num + " is not a prime number"); } else { for(int i = 2; i <= num/2; i++) { if(num % i == 0) { System.out.println( num + " is not prime number"); flag = 1; break; } } if(flag == 0) { System.out.println( num + " is a prime number"); } } } }
Output
11 is a prime number
Method 2 - Find if a number is prime using a function
A program that finds if the given number is prime using a function is given as follow −
Example
public class Example { static int PrimeOrNot(int num) { int flag = 0; if(num == 0||num == 1) { flag = 1; } else { for(int i = 2; i <= num/2; i++) { if(num % i == 0) { flag = 1; break; } } } return flag; } public static void main(String args[]) { int flag, num = 11; flag = PrimeOrNot(num); if(flag == 0) { System.out.println( num + " is a prime number"); } else { System.out.println( num + " is not a prime number"); } } }
Output
11 is a prime number
Advertisements