Project Euler in R Problem 7

Problem 7 of Project Euler asks us to find the 10001st prime number.

The ‘is.prime’ function is the same one that I use in Problem 3. I start the ‘repeat’ loop at 3 so I have to manually set the starting count at 1 (since 2 is prime). I start at 3 because then I can have ‘i’ go up by 2 every iteration (since every prime after 2 is odd). The ‘repeat’ loop then goes through all odd numbers and if they are prime (as determined by the is.prime function I wrote) adds 1 to the count. When the count reaches 10001, the repeat loop breaks and prints the 10001st prime.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
is.prime <- function(x) {
 prime <- 1
 for (i in 2:ceiling(x^.5))
 {
   if (x %% i == 0 && x != 2){
     prime <- 0
   }
 }
 return(prime)
}

n <- 10001
count <- 1
i <- 3

repeat {
 if (is.prime(i) == 1) {
   count <- count + 1
 }
 if (count == 10001) {
   print(i)
   break
 }
 i <- i + 2
}

I’ve had this problem done for a few weeks now and I could have sworn that when I ran it back then, the script completed in only a few milliseconds. Now it’s taking about 5 seconds. Not really sure why it’s slower now but I still get the answer pretty quickly.