The program below displays the first 50 prime numbers in five lines, each contai
ID: 3813529 • Letter: T
Question
The program below displays the first 50 prime numbers in five lines, each containing ten numbers. Modularize it.
public class PrimeNumber {
public static void main(String[] args) {
final int NUMBER_OF_PRIMES = 50; // Number of primes to display
final int NUMBER_OF_PRIMES_PER_LINE = 10; // Display 10 per line
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 ");
// Repeatedly find prime numbers
while (count < NUMBER_OF_PRIMES) {
// Assume the number is prime
boolean isPrime = true; // Is the current number prime?
// Test whether 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
}
}
// Display the prime number and increase the count
if (isPrime) {
count++; // Increase the count
if (count % NUMBER_OF_PRIMES_PER_LINE == 0) {
// Display the number and advance to the new line
System.out.println(number);
}
else System.out.print(number + " ");
}
// Check if the next number is prime
number++;
}
}
}
Explanation / Answer
public class PrimeNumber
{
public static void main(String[] args)
{
final int NUMBER_OF_PRIMES = 50; // Number of primes to display
final int NUMBER_OF_PRIMES_PER_LINE = 10; // Display 10 per line
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 ");
// Repeatedly find prime numbers
while (count < NUMBER_OF_PRIMES)
{
// Display the prime number and increase the count
if (isPrime(number))
{
count++; // Increase the count
if (count % NUMBER_OF_PRIMES_PER_LINE == 0)
{
// Display the number and advance to the new line
System.out.println(number);
}
else System.out.print(number + " ");
}
// Check if the next number is prime
number++;
}
}
static boolean isPrime(int number)
{
// Test whether number is prime
for (int divisor = 2; divisor <= number / 2; divisor++)
{
if (number % divisor == 0)
{
// If true, number is not prime hence return false
return false;
}
}
//number is Prime, return true
return true;
}
}
In the above program, the code to test whether a given number is prime or not is moved to a separate module which is named as isPrime. It is defined to be a static method that takes a number as argument and returns true if the number is a prime number and returns false if the number is not a prime number.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.