Computing Prime Numbers

From CompSciWiki
Revision as of 12:08, 6 April 2010 by ChristopherJ (Talk | contribs)

Jump to: navigation, search

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.

 

SideSectionTitle

float
Taken from http://www.flickr.com/photos/daniello/565304023/

An image or By Students section

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++)
  {

  }
}

Code

Solution Code

Back to the Program-A-Day homepage