7問目

最初の6つの素数を並べると, 2, 3, 5, 7, 11, 13 となり, 6番目の素数は13だということが分かる.
では, 10001番目の素数は何か?

http://projecteuler.net/index.php?section=problems&id=7

prime 関数を使う場合は最初に上限を決めなければいけないのですが, Pierre Duart というフランスの数学者が
 n\(\log{n} + \log{\log{n}} - 1\) < p(n) < n\(\log{n} + \log{\log{n}}\)\quad(n \geq 6,\quad p(n):\quad \text{the n-th prime})
という便利な式を発見しているので, それを拝借.

参考: http://ja.wikipedia.org/wiki/素数定理#.E5.AE.9A.E7.90.86.E3.81.AE.E5.86.85.E5.AE.B9

以下を実行してすんなり終了.

#include <stdio.h>
#include <math.h>
#include <unistd.h>
#include <ctype.h>
#include "prime.h"

#define DEFAULT_COUNT 10001

int version;
int count;

int parseArg(int, char**);
int solveVer00(int);

int main(int argc, char **argv) {
	if (parseArg(argc, argv) == EXIT_FAILURE) {
		return EXIT_FAILURE;
	}
	switch (version) {
	case 0:
		fprintf(stdout, "Solution: %d.\n", solveVer00(count));
		break;
	default:
		break;
	}
	return EXIT_SUCCESS;
}

int solveVer00(int count) {
	int maxValue;
	int i;

	maxValue = count * log(count) + count * log(log(count));
	prime(maxValue);
	for (i = 0; i < count - 1; i++) {
		prime(0);
	}
	return prime(0);
}

int parseArg(int argc, char **argv) {
	int optChar;

	// default values
	version = 0;
	while ((optChar = getopt(argc, argv, "v:")) != -1) {
		switch (optChar) {
		case 'v':
			version = atoi(optarg);
			break;
		case '?':
			if (optopt == 'c') {
				fprintf(stderr, "Option -%c requires an argument.\n", optopt);
			} else if (isprint(optopt)) {
				fprintf(stderr, "Unknown option `-%c'.\n", optopt);
			} else {
				fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt);
			}
			return EXIT_FAILURE;
		default:
			abort();
		}
	}
	if (optind == argc) {
		count = DEFAULT_COUNT;
	} else {
		count = atoi(argv[optind]);
	}	
	return EXIT_SUCCESS;
}