Java – List All Prime Numbers Between 1 to N
Write a Java program to find all prime number between 1 to N. Where N is a number entered by the user at runtime.
Before writing this program you must know What is a prime number? and how to check if a number is prime or not.
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 | import java.util.Scanner; public class PrimeNumber1ToN { private static Scanner scanner = new Scanner( System.in ); public static void main(String[] args) { System.out.println("Enter max number: "); String input = scanner.nextLine(); int maxNumber = Integer.parseInt( input ); System.out.println("List of the prime number between 1 - " + maxNumber); for (int num = 2; num <= maxNumber; num++) { boolean isPrime = true; for (int i=2; i <= num/2; i++) { if ( num % i == 0) { isPrime = false; break; } } if ( isPrime == true ) System.out.println(num); } } } |
Compile and run the program
javac PrimeNumber1ToN.java java PrimeNumber1ToN
Output:
Enter max number: 100 List of the prime number between 1 - 100 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97