java code for first 10 prime nos
- User
java code for first 10 prime nos
Assistant
Certainly! Below is a simple Java program to find and print the first 10 prime numbers.
public class PrimeNumbers { public static void main(String[] args) { int count = 0; // Counter for prime numbers found int number = 2; // Start checking from the first prime number System.out.println("The first 10 prime numbers are:"); while (count < 10) { if (isPrime(number)) { System.out.print(number + " "); count++; } number++; } } // Method to check if a number is prime 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; } }Explanation:
-
Main Method:
- Initializes a counter
countto keep track of how many prime numbers have been found. - Starts checking numbers from 2 upwards.
- Uses a
whileloop to find and print the first 10 prime numbers.
- Initializes a counter
-
isPrime Method:
- Checks if a given number is prime.
- Returns
falsefor numbers less than or equal to 1. - Iterates from 2 to the square root of the number to check for factors. If any factor is found, the number is not prime.
- Returns
trueif no factors are found, indicating the number is prime.
When you run this program, it will print the first 10 prime numbers:
2 3 5 7 11 13 17 19 23 29.-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.