We would like to display the first fifty prime numbers.
An integer greater than 1 is prime if its only positive divisor is 1 or itself.
For example, 2, 3, 5, and 7 are prime numbers, but 4, 6, 8, and 9 are not.
To test whether a number is prime, check whether it is divisible by 2, 3, 4, and so on up to number/2.
If a divisor is found, the number is not a prime.
public class Main { public static void main(String[] args) { int NUMBER_OF_PRIMES = 50; // Number of primes to display int count = 0; // Count the number of prime numbers int number = 2; // A number to be tested for primeness System.out.println("The first 50 prime numbers are \n"); //your code here }//from w ww . j av a 2s . co m }
public class Main { public static void main(String[] args) { int NUMBER_OF_PRIMES = 50; // Number of primes to display int count = 0; // Count the number of prime numbers int number = 2; // A number to be tested for primeness System.out.println("The first 50 prime numbers are \n"); // Repeatedly find prime numbers while (count < NUMBER_OF_PRIMES) { // Assume the number is prime boolean isPrime = true; // Is the current number prime? // Test if number is prime for (int divisor = 2; divisor <= number / 2; divisor++) { if (number % divisor == 0) { // If true, number is not prime isPrime = false; // Set isPrime to false break; // Exit the for loop } } // Print the prime number and increase the count if (isPrime) { count++; // Increase the count System.out.println(number); } // Check if the next number is prime number++; } } }