1. Senior Member
Join Date
Nov 2011
Location
Turkey
Posts
380
Blog Entries
24
Rep Power
9

Hi guys.

I am a beginner in programming, and trying to learn JAVA.

I wrote this code myself where I am looking for prime numbers and printing them on the screen:

Java Code:
```package myPackage;
import java.util.ArrayList;
public class TestClass {

public static void main(String[] args) {

int m;

ArrayList<Integer> controller = new ArrayList<Integer>();

{
{
}
if(controller.contains(0))
{
controller.clear();
}
else
{
controller.clear();
}
}
{
System.out.println(t);
}
}
}```
It works fine, but I have no experienced people around me, so there is no one to say, nobody would do it like this.

Can you have a peek and tell me if this is ok?

2. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,716
Rep Power
18

It's a reasonable approach provided you realise that it relies on building up a list of primes.

Notice that you find *all* of the prime factors of each number (these are the ones where test%m is zero) but in fact you know that the number being tested is *not* a prime once you have found the first prime factor. You could break out of the inner for loop at this point. With that change it might make sense to remove controller altogether.

3. Senior Member
Join Date
Nov 2011
Location
Turkey
Posts
380
Blog Entries
24
Rep Power
9

I am trying it doing without controller, but I am not very successful at it :)

4. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,716
Rep Power
18

That's less important than working on the fact that you can act once you have found the first prime factor.

Java Code:
```for each number
isPrime = true
for each prime
if it is a prime factor
isPrime = false
break // don't check any more primes
if the number isPrime
add it to the primes list```
Does that make sense?

isPrime is behaving a bit like your controller. But it is reset just *before* the inner for loop. And it is reset to true because the function of the inner loop is to detect things which are *not* prime.

5. Senior Member
Join Date
Nov 2011
Location
Turkey
Posts
380
Blog Entries
24
Rep Power
9

Thanks..
I will try this, and hopefully get the idea.

Thank you.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•