1. Home
  2. syntax
  3. Can Someone Please Explain The Logic Behind This Small Java Program Please?

Can Someone Please Explain The Logic Behind This Small Java Program Please?

By WinPie Posted in: syntax

This program is supposed to print out prime numbers from 1 to 50:
Java Syntax (Toggle Plain Text)
public class Break{
public static void main(String[] args){
int i,j;
System.out.println(“Prime numbers between 1 to 50 : “);
for (i = 1;i < 50;i++ ){
for (j = 2;j < i;j++ ){
if(i % j == 0)
{
break;
}
}
if(i == j)
{
System.out.print(" " + i);
}
}
}
}
But why do i have to declare two variables j and i and the get the remainder, and also create loops for each one of them can someone please explain?

Get Chitika Premium
  1. Anonymous Says

    The code, but with comments.
    // Walk i from 1 to 49 inclusive, these are the numbers that will be our potential primes.
    for (i = 1 ; i < 50 ; i++) {
    // Walk j from 2 to i-1 inclusive, these are the potential divisors of i
    for (j = 2 ; j < i ; j++) {
    // If i divided by j has a remainder of 0, then i is divisible by j and so not a prime
    if (i % j == 0) {
    // Jump out of the innermost loop, i.e. that for j
    break;
    }
    }
    // If the “break” was not executed, then the loop will have finished when i == j
    if (i == j) {
    // If the loop exited normally, there is no j that is a divisor of i, so i is prime
    System.out.print(” ” + i);
    }
    }
    }

  2. tfloto Says

    I would never name a class Break. It’s will end up being pretty confusing with the keyword. You need the two loops. one for the test number the other to do the prime test.
    since 1, 2 and 3 are prime and 4 is even you could start at 5.
    for (i = 5;i < 50;i+=2 ) // also skip even numbers you know they aren’t prime.
    you can start the inner loop at three and skip evens they are already taken out by the outer loop. Furthermore you only need the inner loop to go up to the square root of i. And add one for integer truncation so:
    for( j = 3, j < sqrt(i)+1; j+=2)
    {
    if(i % j == 0)
    {
    break;
    }
    I would use a boolean set to false if the inner loop fails and reset to true at the beginning. test for that to determine if you have a prime.

  3. peter Says

    The second is loop is wrong i think,
    for (j = 2;j < i;j++ ){
    and i%j is wrong use
    i%2
    thats simple logic, you are making it complex.Check any C book to get correct logic
    thanks

  4. Lorenzoo Says

    Is that your first time coding? because that is a mess.

More Interesting Things

©2011 Windows Pie, All rights reserved.