Friday, June 11, 2010

Project Euler Problem 7 in C

    ProjectEuler once more! In my opinion, it's logical to do this problem before Problem 3 as Problem 3 requires prime numbers too. Also, Problem 3 has the issue of it being an awkward problem due to the high number... Anyways, here's the Problem:
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6^(th) prime is 13.

What is the 10001^(st) prime number?


    And here's my code:


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

int isPrime(int test)
{
int calculateTo = (int) sqrt(test);

for(int i=3; i<=calculateTo; i+=2)
{
if(test%i==0)
return 0;
}

return 1;
}

int main()
{
int howHigh=10001;
int counter=1;

while (1)
{
for(int i=3; ; i+=2)
{
if( isPrime(i) )
counter++;

if(counter==howHigh)
{
printf("%d\n", i);
return 0;
}
}

}

return 1;
}


Execution Time: 0.187 s

    Not too shabby in my opinion! So that's just about it.
       NotMyFault

No comments:

Post a Comment