Search⌘ K
AI Features

Solution: Get nth Prime Number

Explore how to write a function in C that calculates the nth prime number by checking each number's primality using a helper function. Understand the use of loops and conditionals to count prime numbers until the target is reached.

We'll cover the following...
C
#include <stdio.h>
// The function to be called from within the getNthPrime function
int isPrime(int n)
{
if (n <= 1) return 0;
int i;
for (i = 2; (i * i) <= n; i++)
{
if (n % i == 0) return 0;
}
return 1;
}
// getNthPrime returns the Nth prime
int getNthPrime(int n)
{
int number = 0;
int count = 0; // To keep track of how many primes have been seen so far
while (count < n)
{
// Check if it's the nth prime
if (isPrime(number) == 1)
{
count++;
if(count == n)
{
break;
}
}
number++;
}
return number;
}
int main(void)
{
int n = 10;
printf("%dth prime number is %d\n", n, getNthPrime(n));
return 0;
}
...