# Java prime numbers detector

Write a program that uses two nested for loops and the modulus operator (%) to detect and print prime numbers. A prime numbers are integral numbers that are not evenly divisible by any other numbers except themselves and 1. Use your program to print all the prime numbers from 0 to 10,000. Print 10 numbers per output line, separated by two spaces.- asked by Raj on our Facebook profile

```package com.itcuties.questions;

public static void main(String[] args) {
int found=0;
for (int i=1; i<=10000; i++) {
for (int j=1; j <= i; j++) {
if (i % j == 0 && i != j && j != 1) {	// watch out for the j==1
break;
}
if (i == j)
if ((++found)%10 == 0)
System.out.println(i);
else
System.out.print(i+"  ");
}
}
}
}
```

#### 3 Responses to "Java prime numbers detector"

1. Matteo says:

I’d like to propose 2 improvements on your code:

1. Is there any sense in starting looping from j=1, and checking if j!=1 on the next line? :) Start looping i and j from 2, and you’ll get the same result without that condition (even if is very rarely evaluated).
Same observation apply for checking if “i%j==0 && i!=j”. Just stop looping at “j<i"

2. To state whether a number "a" is prime, you suggest to check if every number, save 1, lesser or equal than "a" can divide "a". And this is bad for computation time. My approach is creating an ArrayList of the prime numbers found, and when checking a number "n", check if any of the prime found and lesser than "(int)sqrt(n)+1" can divide "n". This can be proved to be equivalent to your solution, but runs extremely faster.

Hope this is useful, keep doing such a great work girls!

• itcuties says:

Hello Matteo, thanks a lot for the improvememnts. It’s great to hear that you like what we do :) Take care!

2. Azim says:

can you tell me whats wrong in below script

```class prime
{
public static void main (String []s)
{
boolean prime;
int i, last, n;
System.out.println ("Prime no.s between 3 and 100 are ");
for (n=3;n&lt;100;n=n+2)
{
if ( n &lt;4 )
{
prime=true;
System.out.println(n);
continue;
}
prime = true;
i=3; last = (int)Math.sqrt(n);
do
{
if (n%i == 0)
{
prime=false;
break;
}
i = i+2;
}
while (prime &amp;&amp; (i&lt;last));
if (prime) 	System.out.println (n);
}
}
}
```