Adblock breaks this site

PrimeGenerator java help

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

  1. Xeox

    Xeox Forum Addict
    Banned

    Joined:
    Jun 17, 2010
    Posts:
    357
    Referrals:
    0
    Sythe Gold:
    0
    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!
     
  2. Fate1

    Fate1 Apprentice
    Banned

    Joined:
    Apr 21, 2005
    Posts:
    773
    Referrals:
    2
    Sythe Gold:
    5
    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? >


 
 
Adblock breaks this site