Code:
#include <stdio.h>
#include <stdbool.h>
int main ()
{
int nth_prime;
printf("What prime number do you want to find: ");
scanf("%d", &nth_prime);
int p = 2;
for (int cnt = 0; ; ++p) {
bool isPrime = true;
for(int d = 2; d * d <= p; ++d)
if (p % d == 0) {
isPrime = false;
break;
}
if (isPrime && ++cnt == nth_prime)
break;
}
printf("%d\n", p);
return 0;
}
Or maybe:
Code:
#include <stdio.h>
#include <stdbool.h>
int main()
{
int nth_prime;
printf("What prime number do you want to find: ");
scanf("%d", &nth_prime);
int p = 2;
for (int cnt = 0; cnt < nth_prime; ++p) {
bool isPrime = true;
for(int d = 2; d * d <= p; ++d)
if (p % d == 0) {
isPrime = false;
break;
}
if (isPrime)
++cnt;
}
printf("%d\n", p - 1);
return 0;
}
Or maybe even:
Code:
#include <stdio.h>#include <stdbool.h>
int main()
{
int nth_prime;
printf("What prime number do you want to find: ");
scanf("%d", &nth_prime);
if (nth_prime <= 1) {
printf("none\n");
return 0;
}
if (nth_prime == 1) {
printf("2\n");
return 0;
}
int p = 3;
for (int cnt = 1; cnt < nth_prime; p += 2) {
bool isPrime = true;
for(int d = 3; d * d <= p; d += 2)
if (p % d == 0) {
isPrime = false;
break;
}
if (isPrime)
++cnt;
}
printf("%d\n", p - 2);
return 0;
}