Project Euler Problem 7

What is the 10001st prime number?

PHP Script

<?php
function is_prime($num) {
	$root = ceil(sqrt($num)) + 1;
	$i = 2;
	while($i < $root) {
		if($num % $i == 0) {
			return false;
		}
		$i++;
	}
	return true;
}
$num = 1;
$i = 1;
$run = true;
while($run) {
	$i++;
	if(is_prime($i)) {
		$num++;
	}
	if($num == 10001) {
		$run = false;
	}
}
echo $i;
?>

C Script

#include <stdio.h>
#include <math.h>

int is_prime(int num) {
	int root = ceil(sqrt(num)) + 1;
	int i = 2;
	while(i < root) {
		if(num % i == 0) {
			return 0;
		}
		i++;
	}
	return 1;
}

int main (int argc, const char * argv[]) {
	int num = 1;
	int i = 1;
	int run = 1;
	while(run) {
		i++;
		if(is_prime(i)) {
			num++;
		}
		if(num == 10001) {
			run = 0;
		}
	}
	printf("%d", i);
	return 0;
}

Leave a Reply

Your email address will not be published.