Pages

Thursday, January 19, 2012

Finding Prime Numbers in Java

I was practicing some Java problems the other day; more specifically, I was practicing nested loops. These things are not the easiest to keep track of, but I feel I'm getting better at writing pseudocode and planning the code first instead of just throwing code all over the place! Some exercises I worked on included:

  • Creating a standard 31-day calendar
  • A program that allows the user to input a number, which will then be the dimension for two squares - one empty and one filled (with asterisks)
    • Example: if user types "3," the program spits out: 
    • *** ***
    • *** *  *
    • *** ***
  • A program where the user inputs a number, and the program will print all prime numbers within given number
    • Example: if user types "10," the program prints:
    • 2
    • 3
    • 5
    • 7
That last one gave me the most trouble! Of course, the troubling part was figuring out if a number is prime. Actually, even that wasn't so hard (after I figured it out). It ends up that I somehow forgot that in an if-then statement, not all conditions are checked for truth: as soon as one condition is true, the statements are executed and then it exits!

Put simply: I misused the if-then statement ^_^
Oops!


My excuse is that it was late at night, and I wasn't thinking clearly. :)

Anyway, here is the code I came up with:

//These are possible prime numbers up until the number inputted
for (int prime=2; prime <= input; prime++)
{
      //These are divisors to check if the number is indeed prime
      int divisor;
      for (divisor = 2; divisor <= prime; divisor++)
      {
            //if prime/divisor has remainder of 0
            if (prime % divisor == 0)
           {
                  //AND if prime and divisor are the same number, then it's prime
                  if (prime == divisor)
                  {
                           System.out.println(prime);
                  }
                  //otherwise, it's not. Break out of if-then loop.
                  else
                  {
                            break;
                  }
            }
      }
}

No comments:

Post a Comment