Prime Numbers List from 1 to n
Here you will get the program code to print prime numbers list in java programming.
Program to print Prime Numbers List from 1 to n
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 | import java.util.Scanner; public class PrimeList { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the Number's upper limit (n): "); int n = scanner.nextInt(); scanner.close(); System.out.println("Prime numbers from 1 to " + n + ":"); for (int num = 2; num <= n; num++) { if (isPrime(num)) { System.out.print(num + " "); } } } public static boolean isPrime(int num) { if (num <= 1) { return false; } for (int i = 2; i * i <= num; i++) { if (num % i == 0) { return false; } } return true; } } |
Output
C:\CodeRevise\java>javac PrimeList.java
C:\CodeRevise\java>java PrimeList
Enter the Number’s upper limit (n): 45
Prime numbers from 1 to 45:
2 3 5 7 11 13 17 19 23 29 31 37 41 43
Check out our other Java Programming Examples