• Log in or sign up for an account here: https://www.sythe.org/login

PrimeGenerator java help

Xeox

Forum Addict

Banned
Joined
Jun 17, 2010
Sythe Gold
0
Messages
357
Location
United States
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!
 
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.
 
Runescape Gamblingrunescape gambling
Back
Top