• 10-12-2009, 12:47 PM
Crossfires
Hello everyone,

I'm quite new to Java, i've got the assignment to make a class to show all the primenumbers from 1 to 100. I was stuck on the code and found some help online, i've got the class working working now though i don't understand one part from the application. Can anyone explain?

public static void main(String args[]) {
int number;

//Startwaarde a = 0 en 100 eindwaarde
for (number = 2; number <= 100; number++) {
boolean prime = true;

for (int divider = 2; divider <= divider/2; divider++)
{
if (number % divider == 0)
{
priem = false;
}
}

if (priem)
{
System.out.println(number + " is a primenumberl");
}
}
}
}

int divider = 2; divider <= divider/2; divider++ is the part i don't understand. Why does it say divider/2; ? Please keep in mind i'm a beginner so be gentle with your explaination.

Thanks!
• 10-12-2009, 01:21 PM
Vio
I think "divider/2" is wrong and should be "number/2", maybe you'll understand now.
• 10-12-2009, 01:25 PM
Crossfires
Correct it should be number / 2 but that is my typo. It should say that but i still don't understand.
• 10-12-2009, 01:31 PM
r035198x
1.) Please use code tags when posting code.
2.)That's the problem of ripping codes off the internet and passing it in as your own.
Better try to write it on your own next time.
3.)Run that loop manually writting values of all the relevant variables in a table to see what they are at each stage of the loop. That way you will understand the code more.

P.S You probably didn't post the exact code you've got too.
• 10-12-2009, 01:33 PM
Vio
To explain it simply I'll use an example. For example you reach number = 18.
Then why should you check if it's dividable by 17,16,15,14,13,12,11,10 ? You are sure 18 is not dividable by them, so you only have to check the numbers from 18/2 = 9 till 2. And this is correct for every number.
• 10-12-2009, 01:39 PM
Crossfires
Thank you for you explaination, this is what i thought. Though if, for some reason you are inefficient, how would that line of the code look if you would just check devisions 17, 16 etc. as well. If i try to change the code to do this like change number /2 to just number, it won't work. I don't understand why
• 10-12-2009, 01:42 PM
Vio
And what goes wrong then? I guess you get no prime numbers then?
• 10-12-2009, 01:52 PM
Crossfires
Yes, it wont work
• 10-12-2009, 02:10 PM
Crossfires
I now understand why that won't work because if the number is divided by itself you will have module 0 and the prime will be false (even if it's not.) Thank you so much for your help.
• 10-12-2009, 06:06 PM
xcallmejudasx
not sure if this was just a typo but your variable is declared as prime and when checking you have it spelled priem