Writing Algorithms to Find N Prime Numbers
Prime numbers are those greater than 1 that have no divisors other than 1 and themselves. To find the first N prime numbers, we’ll need to implement a method that checks for primality:
Example: Generate First N Prime Numbers
public class FirstNPrimeNumbers {
public static void main(String[] args) {
int N = 10; // Specify how many prime numbers to generate
int count = 0;
int number = 2; // Start checking for prime from the first prime number
System.out.println("First " + N + " Prime Numbers:");
while (count < N) {
if (isPrime(number)) {
System.out.print(number + " ");
count++;
}
number++;
}
}
public 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;
}
}
Output:
First 10 Prime Numbers:
2 3 5 7 11 13 17 19 23 29
This code defines a method isPrime to check for prime numbers, and uses a while loop to count and display the first N primes. Notice how the loop continues until we reach the desired count of prime numbers.
Using Conditionals to Distinguish Between Even, Odd, and Prime
Finding and printing even, odd, and prime numbers can also be combined in a single program. Here’s an enhanced example demonstrating this:
Example: Distinguishing Even, Odd, and Prime Numbers
public class NumberClassification {
public static void main(String[] args) {
int N = 20; // We can analyze up to 20
System.out.println("Numbers from 1 to " + N + ":");
for (int i = 1; i <= N; i++) {
StringBuilder output = new StringBuilder(i + " is ");
if (isPrime(i)) {
output.append("prime");
} else if (isEven(i)) {
output.append("even");
} else {
output.append("odd");
}
System.out.println(output);
}
}
public static boolean isEven(int number) {
return number % 2 == 0;
}
public 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;
}
}
Output:
Numbers from 1 to 20:
1 is odd
2 is prime
3 is prime
4 is even
5 is prime
6 is even
7 is prime
8 is even
9 is odd
10 is even
11 is prime
12 is even
13 is prime
14 is even
15 is odd
16 is even
17 is prime
18 is even
19 is prime
20 is even
In this program, we classify numbers from 1 to 20 as either prime, even, or odd using a combination of conditionals and method calls.