1. Introduction
In this post, we will write a Java program to generate all prime numbers up to a given number n. A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers other than itself and 1.
2. Program Steps
1. Declare a class named PrimeGenerator.
2. Inside this class, define the main method.
3. Inside the main method, define a variable n to which up to we have to find the prime numbers.
4. Create a loop to iterate through all numbers from 2 to n.
5. For each number, check whether it is prime or not.
6. If it is prime, print the number.
3. Code Program
public class PrimeGenerator { // Step 1: Declare a class named PrimeGenerator
// Method to check whether a number is prime or not
static boolean isPrime(int num) {
if (num <= 1) return false;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) return false;
}
return true;
}
public static void main(String[] args) { // Step 2: Define the main method
int n = 50; // Step 3: Define a variable n
// Step 4: Create a loop to iterate through all numbers from 2 to n
for (int i = 2; i <= n; i++) {
// Step 5: For each number, check whether it is prime or not
if (isPrime(i)) {
// Step 6: If it is prime, print the number
System.out.print(i + " ");
}
}
}
}
Output:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
4. Step By Step Explanation
– Step 1: A class named PrimeGenerator is declared.
– Step 2: The main method is defined inside the PrimeGenerator class.
– Step 3: We define a variable n and assign it a value of 50.
– Step 4: A for loop is used to iterate through all numbers from 2 to n.
– Step 5: For each number in the loop, we check whether it is prime or not using the isPrime method.
– Step 6: If the number is prime, it gets printed to the console.
– The isPrime method checks whether a number is prime by ensuring it is not divisible by any number from 2 to the square root of the number itself.