Solution to Project Euler 7


Improve your writing skills in 5 minutes a day with the Daily Writing Tips email newsletter.

Here’s the description of the Problem 7:

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10 001st prime number?

In order to find the solution I wrote a simple function to test whether a number n is prime or not, and then I iterated through all the integers increasing the counter every time a prime is found, until the 10001 was found:

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

int isPrime(num){
  int i;

  if (num==2)
    return 1;

  for (i=2;i<sqrt(num)+1;i++){
    if (num%i==0)
      return 0;
    } 

  return 1;
}

int main(){
  int i,counter,ans;
  ans=0;
  counter=0;

  for (i=2;i<200000;i++){
    if (isPrime(i)==1){
      counter++;
      ans=i;      
    }
    if (counter==10001){
      break;
    }
  }

  printf("%dn",ans);
  return 0;
}

One thought on “Solution to Project Euler 7

Leave a Reply

Your email address will not be published. Required fields are marked *