In this tutorial you will learn about the Java Program to display alternate prime numbers and its application with practical example.
In this tutorial, we will learn to create a Java Program to display alternate prime numbers using Java programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following Java programming topics:
- Java Operators.
- Basic Input and Output function in Java.
- Class and Object in Java.
- Basic Java programming.
- If-else statements in Java.
- For loop in Java.
Prime Number:
A prime number is a number such that is either divides by 1 or itself(Number itself).
For example, 2, 3, 5, 7,11,13 and etc. are prime numbers.
Java Program to display alternate prime numbers
In this program we would find alternate Prime number Between given number .first of we would take a value from user and find display alternate prime numbers, Let’s have a look at the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
// java program to find odd number between 1 to N import java.util.Scanner; class Alt_prime { //functon for checking prime number... static int Prime(int number) { int i, count = 0; for(i = 2; i<= number / 2; i++) { if(number % i == 0) { count = 1; break; } } /* If the value of count is 0 then the given number is prime */ if(count == 0) return 1; else return 0; } //Method for printing alternate prime numbers static void Alt_Prime(int number) { int temp = 2; for(int n = 2; n <= number-1; n++) { //checking each number whether it is prime or not if (Prime(n) == 1) { // if temp is even then only print the prime number if (temp % 2 == 0) System.out.print(n + " "); temp ++; } } } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter any value "); int number = in.nextInt(); System.out.print("Alternate prime numbers upto " + number+" are: "); Alt_Prime(number); } } |
Output
Alternate Prime number between given number are
In the above program, we have first declared and initialized a set variables required in the program.
- number= it will hold entered number.
- count = it will count number is prime or not.
- temp = it print prime number with in the given range.
- n = for iteration.
After that we take a number from user we will print prime number between the given range.
now we will pass the given range to function Alt_Prime(number) where we find prime number between given range.
with in the function we will call function named with Prime() where we calculate Prime numbers.
This function find Prime number within the range and returns true to Alt_Prime() function .
where we print Prime numbers.