# Trying to add a loop to a Java Program.

Discussion in 'OT Technology' started by MattC, Sep 16, 2003.

1. ### MattCgotta love the prewar

Joined:
Nov 6, 2001
Messages:
276
0
I'm trying to write a program using that will spit out numbers that are prime. Like you give it an input of "4" and the program will spit out the first four prime numbers.

The first thing I'm trying to do though is make sure it will spit out only prime numbers. I've made a little program to do that. Only problem is it won't print the first four prime numbers b/c of the parameters I set. (everything after that is fine)

Any ideas of how to add the first four numbers in there to make it say they are prime? Should I use a different type of statement.

Also, once I get this to work, anyone have any ideas of how to get it to loop to print out primes in succession (the most it will have to do is 15-20 numbers)?

Code:
``` if ((number %2 != 0)&&(number %3 != 0)&&(number %5 != 0)&&(number %7 != 0))
{
System.out.println(number + " is a prime number");
}
else
{

System.out.println("Sorry " + number + " is not a prime number");

}```

2. ### 5Gen_PreludeThere might not be an "I" in the word "Team", but

Joined:
Mar 14, 2000
Messages:
14,519
1
Location:
The first thing you should do is figure out how to print n prime numbers - that will solve all of your problems.

Code:
```function printprimes(primes as integer)

dim i as long
dim counter as integer

i=1
do while primes <> counter
if prime(i) then counter = counter + 1
i=i+1
loop

end function

function prime(checkprime as long)

end function```

3. ### MattCgotta love the prewar

Joined:
Nov 6, 2001
Messages:
276
0
Thanks for the info, unfortunately I can barely understand java, so what you wrote doesn't help me at all.

I guess I need help like, "use a while loop to check blah blah blah, then......"

4. ### crotchfruitGuest

what 5gen is saying is that you need a separate member function that returns a boolean (true/false) depending on whether an integer input is prime or not.. i.e. "public boolean isPrime(int n)"

then, in the main loop, you can do something like:
Code:
```int numprimes = 0;
int cur = 2;
while (numprimes < 4)
{
if (isPrime(cur))
{
System.out.println(cur + " is prime.");
numprimes++;
}
cur++;
}
```

5. ### 5Gen_PreludeThere might not be an "I" in the word "Team", but

Joined:
Mar 14, 2000
Messages:
14,519
1
Location:
Well you don't NEED a separate function, but for testing purposes it's much easier to isolate and in the end make your prime code more efficient in finding primes (there's some really cool algorithms out there that would make us simple minded idiots spin).

BTW, good call on the first number being 2, not 1

7. ### Penguin ManProtect Your Digital Liberties

Joined:
Apr 27, 2002
Messages:
21,696
0
Location:
Edmonton, AB
Yep, I have one around here somewhere... Has something to do with square roots and 6 or something.

Joined:
Nov 6, 2001
Messages:
276