In this tutorial you will learn about the Prime Number Up to N Terms Program in Java and its application with practical example.
In this tutorial, we will learn to create a Java Prime Number Up to N Terms Program in Java.
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
- Class and Object.
- Basic Java programming.
- String.
- User define Function.
What is a Prime Number?
A number is called a prime number if it fully divisible by the number itself or 1 only.
For example :-> 7 is a prime number, it is fully divisible by 7 only between 2-7 and “1” only.
Prime Number Up to N Terms Program in Java
In this program we will find prime n umber between 1-N. We would first declared and initialized the required variables. Next, we would ask user to enter value of N. let have a look at 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 |
// java program to find n prime numbers import java.util.Scanner; public class Prime_Number { // declaring variables and taking value from user.. private static Scanner scanner = new Scanner( System.in ); public static void main(String[] args) { System.out.println("Enter Size of N: "); String input = scanner.nextLine(); int n = Integer.parseInt( input ); System.out.println("List of prime number between 1 - " + n); // condttion for prime number.. for (int number = 2; number <= n; number++) { boolean p = true; for (int i=2; i <= number/2; i++) { if ( number % i == 0) { p = false; break; } } if ( p == true ) System.out.println(number); } } } |
Output
N Prime Number
In the above program, we have first declared and initialized a set variables required in the program.
- n = it will hold entered N size.
- number = For iteration till N.
- p= for condition of prime.
After that we declare variables and taking value from user.
Then we check condition for prime between 2 to N.
Here we iterate loop form two to given number and check the condition for every number that is prime or not and last we will print list of all prime number between 1 to N as shown in above image.