Java Program - Find all Prime Numbers in a given Interval
A Prime number is a natural number greater than 1 and divisible by 1 and itself only, for example: 2, 3, 5, 7, etc.
Objective: Write a Java code to find all prime numbers in a given internal.
Method 1: Using function to find prime number
In the example below, a function called primenumber() is created which takes a number as argument and checks it for prime number by dividing it with all natural numbers starting from 2 to N/2.
public class MyClass { static void primenumber(int MyNum) { int n = 0; for(int i = 2; i < (MyNum/2+1); i++) { if(MyNum % i == 0){ n++; break; } } if (n == 0){ System.out.print(MyNum + " "); } } public static void main(String[] args) { int x = 10; int y = 50; System.out.println("Prime numbers between "+ x + " and " + y + " are: "); for(int i = x; i < y + 1; i++) { primenumber(i); } } }
The above code will give the following output:
Prime numbers between 10 and 50 are: 11 13 17 19 23 29 31 37 41 43 47
Method 2: Optimized Code
- Instead of checking the divisibility of given number from 2 to N/2, it is checked till square root of N. For a factor larger than square root of N, there must the a smaller factor which is already checked in the range of 2 to square root of N.
- Except from 2 and 3, every prime number can be represented into 6k ± 1.
public class MyClass { static void primenumber(int MyNum) { int n = 0; if (MyNum == 2 || MyNum == 3){ System.out.print(MyNum + " "); } else if (MyNum % 6 == 1 || MyNum % 6 == 5) { for(int i = 2; i*i <= MyNum; i++) { if(MyNum % i == 0){ n++; break; } } if (n == 0){ System.out.print(MyNum + " "); } } } public static void main(String[] args) { int x = 100; int y = 200; System.out.println("Prime numbers between "+ x + " and " + y + " are: "); for(int i = x; i < y + 1; i++) { primenumber(i); } } }
The above code will give the following output:
Prime numbers between 100 and 200 are: 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199
Recommended Pages
- Java - Swap two numbers
- Java Program - Fibonacci Sequence
- Java Program - Insertion Sort
- Java Program - Find Factorial of a Number
- Java Program - Find HCF of Two Numbers
- Java Program - Merge Sort
- Java Program - Shell Sort
- Stack in Java
- Queue in Java
- Java Program - Find LCM of Two Numbers
- Java Program - To Check Whether a Number is Palindrome or Not
- Java Program - To Check Whether a String is Palindrome or Not
- Java Program - Heap Sort
- Java Program - Quick Sort
- Java - Swap Two Numbers without using Temporary Variable
- Java Program - To Check Armstrong Number
- Java Program - Counting Sort
- Java Program - Radix Sort
- Java Program - Find Largest Number among Three Numbers
- Java Program - Print Floyd's Triangle