Hi everyone,
I'm taking an intro Java course, which I'm quite honestly, not very good at it. Anyways, we have this Prime # program that counts all the Prime #'s up to 50 using a for loop:
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 \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 if (count % NUMBER_OF_PRIMES_PER_LINE == 0) { // Print 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++; } } }
The task is to convert the for-loop under the comment //Test if number is prime, into a while-loop, which I can't seem to get right.
This is how I changed the code:
public class Lab3_2 { 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 \n"); // Repeatedly find prime numbers while (count < NUMBER_OF_PRIMES) { // Assume the number is prime isPrime = true; // Is the current number prime? // Test if number is prime int divisor = 2; while (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 if (count % NUMBER_OF_PRIMES_PER_LINE == 0) { // Print 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++; } } }
Any assistance is greatly appreciated!!
Sam