# Get a prime number by its index in the prime sequence

Page 1 of 1

## 2 Replies - 1568 Views - Last Post: 23 July 2012 - 11:45 AM

### #1 RodgerB

• D.I.C Lover

Reputation: 66
• Posts: 2,284
• Joined: 21-September 07

# Get a prime number by its index in the prime sequence

Posted 10 May 2008 - 03:58 PM

Description: 1) Copy and paste the functions into a class. 2) Read how to call them.Get a prime number by the position it is in, in the prime number sequence.
```// The function we will be using to get the prime
// by its index in the prime number sequence.
public static int getPrime(int index)
{
int i = 2, counter = 0, val = 0;

while (counter != index)
{
if (isPrime(i))
{
val = i;
counter++;
}
i++;
}

return val;
}

// Function to check if a number is prime.
private static bool isPrime(int n)
{
for (int i = 2; i < n; i++)
if ((n % i) == 0)
return false;

return true;
}

// Example Usage:
MessageBox.Show(getPrime(10).ToString());
```

Is This A Good Question/Topic? 0

## Replies To: Get a prime number by its index in the prime sequence

### #2 SuperUltraMegaMan

Reputation: 0
• Posts: 0
• Joined: 23-July 12

## Re: Get a prime number by its index in the prime sequence

Posted 23 July 2012 - 11:40 AM

Actually, you can stop checking to see if a number is prime at n / 2. A better isPrime(int n) would be: ``` // Function to check if a number is prime. private static bool isPrime(int n) { for (int i = 1; i < n\2; ++i) if ((n % i) == 0) return false; return true; }```

### #3 SuperUltraMegaMan

Reputation: 0
• Posts: 0
• Joined: 23-July 12

## Re: Get a prime number by its index in the prime sequence

Posted 23 July 2012 - 11:45 AM

Sorry. Error in method and can't delete post. Ugh. i++ must occur after the test (%). // Function to check if a number is prime. private static bool isPrime(int n) { for (int i = 2; i < n\2; ) if ((n % i++) == 0) return false; return true; }