# help with a for loop

• October 3rd, 2010, 12:06 AM
newbie79
help with a for loop
I have this assignment to do a loop to determine all the prime numbers from 1 to 1000, but to try it, i did my loop from 1 to 10.

This is my code:

public class premier
{
public static void main (String [] args)
{
int diviseur = 0;
int resultat = 0;
int nombre = 0;
int diviseurs = 0;
int nbdiviseurs = 0;

for(int valeur = 1; valeur <= 10; valeur++)
{
for(diviseur = 2; diviseur < valeur; diviseur++)
{
resultat = valeur % diviseur;

if(resultat != 0)
{
System.out.println(valeur+" est premier");
}

else
{

diviseurs = diviseur;
System.out.println(valeur+ " est divisible par : "+diviseurs);
}
}
}
}
}

However, because my system.out.print is i the diviseur loop. it prints for every diviseur

Print:

3 est premier
4 est divisible par : 2
4 est premier
5 est premier
5 est premier
5 est premier
6 est est divisible par : 2
6 est divisible par : 3
6 est premier
6 est premier
...

However, I am supposed to do

3 est premier
4 est divisible par : 2, soit 1 diviseurs
5 est premier
6 est divisible par 2, 3, soit 2 diviseurs
...

However everytime I try printing out of the diviseur loop, the modulo is not the right value anymore so it prints est premier for all values.

thks a lot
• October 3rd, 2010, 12:40 AM
msa0127a
Re: help with a for loop
Hi,

here is a simple code that displays prime number from 1-1000. You can change the UPPER_LIMIT to any number. Since I don't speak french (I think it is french?), your code is a bit confusing for me. This code is doesn't use advanced java coding. I hope you understand the drift of it.
Hope it helps

here is the code:

public class Main {

private final int UPPER_LIMIT = 1000;

public void calculatePrimeNumbers() {

int i = 0;
int primeNumberCounter = 0;

while (++i <= UPPER_LIMIT) {

int i1 = (int) Math.ceil(Math.sqrt(i));

boolean isPrimeNumber = false;

while (i1 > 1) {

if ((i != i1) && (i % i1 == 0)) {
break;
} else if (!isPrimeNumber) {
}

--i1;
}

System.out.println(i);
}
}

System.out.println("Nr of prime numbers found: " + primeNumberCounter);
}

public static void main(String[] args) {