Code Snippets

  

C# Source Code


Welcome to Dream.In.Code
Getting C# Help is Easy!

Join 119,059 C# Programmers for FREE! Ask your question and get quick answers from experts. There are 1,471 online right now! We've got more than 500 tutorials and 2,000 snippets. Join and find out why Dream.In.Code is the #1 programming help community on the internet! Registration is fast and FREE... Join Now!




Get a prime number by its index in the prime sequence

Get a prime number by the position it is in, in the prime number sequence.

Submitted By: RodgerB
Actions:
Rating:
Views: 410

Language: C#

Last Modified: May 11, 2008
Instructions:
1) Copy and paste the functions into a class.
2) Read how to call them.

Snippet


  1. // The function we will be using to get the prime
  2. // by its index in the prime number sequence.
  3. public static int getPrime(int index)
  4. {
  5.     int i = 2, counter = 0, val = 0;
  6.  
  7.     while (counter != index)
  8.     {
  9.         if (isPrime(i))
  10.         {
  11.             val = i;
  12.             counter++;
  13.         }
  14.         i++;
  15.     }
  16.  
  17.     return val;
  18. }
  19.  
  20. // Function to check if a number is prime.
  21. private static bool isPrime(int n)
  22. {
  23.     for (int i = 2; i < n; i++)
  24.         if ((n % i) == 0)
  25.             return false;
  26.  
  27.     return true;
  28. }
  29.  
  30. // Example Usage:
  31. MessageBox.Show(getPrime(10).ToString());

Copy & Paste


Comments


There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month