PrimeGenerator java help

Discussion in 'Programming General' started by Xeox, Dec 5, 2010.

PrimeGenerator java help
  1. Unread #1 - Dec 5, 2010 at 2:52 PM
  2. Xeox
    Joined:
    Jun 17, 2010
    Posts:
    357
    Referrals:
    0
    Sythe Gold:
    0

    Xeox Forum Addict
    Banned

    PrimeGenerator java help

    I am having a hard time figuring out an algorithm to calculate the prime numbers between 2 and x (where x is a number entered by the user and is exclusive).

    I can't seem to figure out how to get the program to print the right numbers.

    Example:
    Enter a number: 20
    Prime Numbers less than 20:

    2
    3
    5
    7
    11
    13
    17
    19

    We are using loops this chapter (while/for/do), but I understand how I am going to loop it.

    for (int i = 1 (unsure about the starting number); i < number (number entered ex: 20); i++)
    {
    //run the method that returns the right values
    }

    The for loop would be in the main class, but the method would be in a separate class called PrimeGenerator.

    If you're confused by how I am asking the question you can just discard it, but if you know how to make an algorithm that can help me out here that would be great!
     
  3. Unread #2 - Dec 5, 2010 at 4:45 PM
  4. Fate1
    Joined:
    Apr 21, 2005
    Posts:
    773
    Referrals:
    2
    Sythe Gold:
    5

    Fate1 Apprentice
    Banned

    PrimeGenerator java help

    You can make a boolean method that take's an int x as a parameter and loop it x amount of times while checking if it is prime. Such as:

    Code:
    boolean isPrime = true;
            for (int i = 2; i < number; i++) {
                if ((number != i) && (number % i == 0)) {
                    isPrime = false;
                    break;
                }
            }
    Once it runs through the loop return isPrime.
     
< Tic Tac Toe help | Sythe programming contests? >

Users viewing this thread
1 guest


 
 
Adblock breaks this site