Skip to content

Instantly share code, notes, and snippets.

@peat-psuwit
Created May 14, 2014 14:43
Show Gist options
  • Save peat-psuwit/eb6174c91a0f0c47d059 to your computer and use it in GitHub Desktop.
Save peat-psuwit/eb6174c91a0f0c47d059 to your computer and use it in GitHub Desktop.
เฉลยข้อ Prime ตัวที่ n การแข่งขัน TOI10
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
unsigned int *primes;
unsigned int primesCount=1, primesLimit=16;
unsigned int primeNeeded;
unsigned int currNumber, currPrime;
double currNumberSqrt;
int isPrime;
primes = malloc(primesLimit * sizeof(unsigned int));
primes[0] = 2;
scanf("%u", &primeNeeded);
currNumber = 3;
while (primesCount < primeNeeded) {
currNumberSqrt = sqrt(currNumber);
currPrime = 0;
isPrime = 1;
while (primes[currPrime] <= currNumberSqrt) {
if (currNumber % primes[currPrime] == 0) {
isPrime = 0;
break;
}
currPrime++;
}
if (isPrime) {
if (primesCount == primesLimit) {
primesLimit *= 2;
primes = realloc(primes, primesLimit * sizeof(unsigned int));
}
primes[primesCount] = currNumber;
primesCount++;
}
currNumber += 2;
}
printf("%u\n", primes[primeNeeded-1]);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment