- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- Different Methods to find Prime Number in Python
- Different Methods to find Prime Number in Python Program
- Analysis of Different Methods to find Prime Number in Python
- Analysis of Different Methods to find Prime Number in Python program
- Different Methods to find Prime Numbers in C#
- Java methods to check for prime and find the next prime
- Java Program to find largest prime factor of a number
- Prime number program in Java.
- Java program to check for prime and find next Prime in Java
- Java program to print a prime number
- Use overloaded methods to print array of different types in Java
- Java Program to find Product of unique prime factors of a number
- 5 Different methods to find length of a string in C++?
- I am the smallest number, having four different prime factors. Can you find me?
- 5 Different methods to find the length of a string in C++?

Advertisements