Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: Need help.. Counting Prime #'s up to 50 w/while loop

  1. #1
    Junior Member
    Join Date
    Oct 2010
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Need help.. Counting Prime #'s up to 50 w/while loop

    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
    Last edited by stommy989; October 5th, 2010 at 08:09 PM.


  2. #2
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Need help.. Counting Prime #'s up to 50 w/while loop

    A few things:

    First off, it is SO refreshing to see a first time poster post correctly. It is very appreciated.

    Second, does your changed code work?

    Third, if it doesn't work, here is basically what you need to do. Essentially, you need to check to see if each number between 2 and half of the number is divisible. Now, I believe you are doing this now, but there is a little something you can do to make it faster. You don't have to check every number.
    The very nice thing about even numbers is:
    If the number is divisible by 2, it will not be prime.
    But if the number is not divisible by 2, it will also not be divisible by any other even number, as all even numbers are divisible by 2. So if you are after making it a little faster, you can actually count by 2s instead of 1s. Even better than that, if I am not mistaking, every number between 2 and 9 serve as a standard set of possible divisibles. Where if the number is not divisible by any numbers below 10, and if it is not prime, then it must be divisible by another prime number. Essentially, after getting to 11, there is no need to check every number but rather only the prime numbers for divisibility. This way of finding prime numbers would require you to keep an array of prime numbers you find, and it is really only practical if you are looking for super high prime numbers. It is an interesting thought though.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  3. #3
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Need help.. Counting Prime #'s up to 50 w/while loop

    Quicker method: Sieve of Eratosthenes

    A simple method for converting a for-loop into a while loop:

    for(init; condition; increment)
    {
     // loop code
    }

    init;
    while(condition)
    {
        // loop code
        increment;
    }

  4. #4
    Junior Member
    Join Date
    Oct 2010
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Need help.. Counting Prime #'s up to 50 w/while loop

    I must be getting pretty close... here's my code now:

    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
          boolean 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++;
        }
      }
    }

    Here's the output I get:

    The first 50 prime numbers are

    2 3 4 5 7 11 13 17 19 23
    29 31 37 41 43 47 53 59 61 67
    71 73 79 83 89 97 101 103 107 109
    113 127 131 137 139 149 151 157 163 167
    173 179 181 191 193 197 199 211 223 227
    It works and it's exactly what it's supposed to look like, but for some reason I'm just getting the number 4 in the code...which isn't a prime...

  5. #5
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Need help.. Counting Prime #'s up to 50 w/while loop

    Why do you increment divisor prior to checking if number is prime or not?
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  6. #6
    Junior Member
    Join Date
    Oct 2010
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Need help.. Counting Prime #'s up to 50 w/while loop

    I actually fixed it today...the divisor++ should have been outside of the IF statement (in bold where it should be).

    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
          boolean isPrime = true; // Is the current number prime?
     
          // Test if number is prime
          int divisor = 2;
          while (divisor <= number / 2){
            if (number % divisor == 0) { // If true, number is not prime
              isPrime = false; // Set isPrime to false
              break; // Exit the for loop
            }
         [B] divisor++;[/B]
          }
     
          // 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++;
        }
      }
    }

    Sam

Similar Threads

  1. Help with Arrays - Counting elements
    By ShakeyJakey in forum Collections and Generics
    Replies: 7
    Last Post: August 8th, 2010, 04:09 PM
  2. Generate prime numbers within fiboncacci series?
    By Manish87 in forum Algorithms & Recursion
    Replies: 5
    Last Post: August 7th, 2010, 12:24 PM
  3. Question: counting
    By miss confused in forum Java Theory & Questions
    Replies: 2
    Last Post: July 30th, 2010, 05:38 PM
  4. counting words of a text file
    By maybach230 in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: May 6th, 2010, 03:40 PM
  5. Need Help - Factoring & Prime Finding Code
    By prodigytoast in forum Algorithms & Recursion
    Replies: 5
    Last Post: November 5th, 2009, 07:38 AM