Difference between revisions of "Computing Prime Numbers"

From CompSciWiki
Jump to: navigation, search
Line 7: Line 7:
  
 
|SideSection=
 
|SideSection=
[[Image:Wiki_loops02.jpg|center]]<BR>
+
[[Image:Wiki_loops01.jpg|center]]<BR>
  
 
|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.
 
|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.

Revision as of 16:26, 7 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