Problem

(Revise Listing 1, PrimeNumber.java) Listing 1 determines whether a number n is prime by c...

(Revise Listing 1, PrimeNumber.java) Listing 1 determines whether a number n is prime by checking whether 2, 3, 4, 5, 6, . . . , n/2 is a divisor. If a divisor is found, n is not prime. A more efficient approach is to check whether any of the prime numbers less than or equal to 2n can divide n evenly. If not, n is prime. Rewrite Listing 1 to display the first 50 prime numbers using this approach. You need to use an array to store the prime numbers and later use them to check whether they are possible divisors for n.

LISTING 1 PrimeNumber.java

1 public class PrimeNumber {

2 public static void main(String[] args) {

3 final int NUMBER_OF_PRIMES = 50; // Number of primes to display

4 final int NUMBER_OF_PRIMES_PER_LINE = 10; // Display 10 per line

5 int count = 0; // Count the number of prime numbers

6 int number = 2; // A number to be tested for primeness

7

8 System.out.println("The first 50 prime numbers are \n");

9

10 // Repeatedly find prime numbers

11 while (count

12 // Assume the number is prime

13 boolean isPrime = true; // Is the current number prime?

14

15 // Test whether number is prime

16 for (int divisor = 2; divisor <= number / 2; divisor++) {

17 if (number % divisor == 0) { // If true, number is not prime

18 isPrime = false; // Set isPrime to false

19 break; // Exit the for loop

20 }

21 }

22

23 // Display the prime number and increase the count

24 if (isPrime) {

25 count++; // Increase the count

26

27 if (count % NUMBER_OF_PRIMES_PER_LINE == 0) {

28 // Display the number and advance to the new line

29 System.out.println(number);

30 }

31 else

32 System.out.print(number + " ");

33 }

34

35 // Check if the next number is prime

36 number++;

37 }

38 }

39 }

Step-by-Step Solution

Request Professional Solution

Request Solution!

We need at least 10 more requests to produce the solution.

0 / 10 have requested this problem solution

The more requests, the faster the answer.

Request! (Login Required)


All students who have requested the solution will be notified once they are available.
Add your Solution
Textbook Solutions and Answers Search
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT