Difference between revisions of "Computing Prime Numbers"

From CompSciWiki
Jump to: navigation, search
Line 34: Line 34:
 
|SolutionCode=
 
|SolutionCode=
 
<pre>
 
<pre>
public class PrimeNumbers
+
public class NewClass {
{
+
 
   public static void main(String args[])
 
   public static void main(String args[])
 
   {
 
   {
     boolean curPrime = true;
+
     boolean curPrime = true;   //check to see if it's true
     for(int i=1;i<=20;i++)
+
 
 +
    //we will be printing out the numbers later
 +
    //we just don't want to have this print in the loop
 +
    System.out.print("The prime numbers are: ");
 +
   
 +
    //the for loop for checking each number
 +
    //you can omit 1 because it is not a prime number!
 +
     for(int i=2;i<=20;i++)
 
     {
 
     {
       for(int j=1;i<j;j++)
+
      curPrime = true;          //number is innocent until proven guilty
 +
 
 +
      //loop to seek first number
 +
       for(int j=1;j<i;j++)
 
       {
 
       {
         for(int k=0;i<j;k++)
+
        //loop to seek second number
 +
         for(int k=0;k<=j;k++)
 
         {
 
         {
 +
          //if both numbers equal i
 
           if(j*k == i)
 
           if(j*k == i)
 
           {
 
           {
             curPrime = false;
+
             curPrime = false;   //this criminal is NOT a prime number
 
           }
 
           }
 
         }
 
         }
 
       }
 
       }
 +
     
 +
      //print out each number if it is prime
 
       if(curPrime)
 
       if(curPrime)
 
       {
 
       {
Line 56: Line 69:
 
       }
 
       }
 
     }
 
     }
 +
    //it is good form to always end the line you print on
 +
    System.out.println();
 
   }
 
   }
 
}
 
}

Revision as of 10:09, 8 April 2010

Back to the Program-A-Day homepage

Problem

It is often useful to compute prime numbers (e.g. Encryption). Compute prime numbers up to 20 by use of nested loops.

 

Getting Started

Wiki loops01.jpg

Solution

You start by using a for loop that will count from 1 to 20. Everything we do inside this loop will be done on each number.

forIint i = 1;i <= 20;i++)
{

}

Since any number that is only the product of 1 and itself we need a way to find the sum of all numbers that are less then itself. This will be to ensure that there are no other products that equal to that number. We can do this by use of a loop.

for(int i = 1;i <= 20;i++)
{
  for(int j = 1;j<i;j++)
  {

  }
}

The next step is to add a third for loop

Code

Solution Code

Back to the Program-A-Day homepage