# Euler Problem 7: 10,001st Prime and Sexy Primes

Euler problem 7 asks us to generate ten thousand prime numbers.

## Euler Problem 7 Definition

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 1,0001st prime number?

## Solution

TheĀ `is.prime` function determines whether a number is a prime number by checking that it is not divisible by any prime number up to the square root of the number. The Sieve of used in Euler Problem 3 generates the prime numbers. This problem can only be solved using brute force becauseĀ prime gaps (sequence A001223 in the OEIS) do not follow a predictable pattern. You can download the latest version of this code from GitHub.

```is.prime &lt;- function(n) {
primes &lt;- esieve(ceiling(sqrt(n)))
prod(n %% primes! = 0) == 1
}
i &lt;- 2 # First Prime
n &lt;- 1 # Start counter
while (n &lt; 10001) { # Find 10001 prime numbers
i &lt;- i + 1 # Next number
if(is.prime(i)) { # Test next number
n &lt;- n + 1 # Increment counter
i &lt;- i + 1 # Next prime is at least two away
}
}
```

## Sexy Primes

The largest prime gap for the first 10,001 primes is 72. Sexy primes with a gap of 6 are the most common and there are 1270 twin primes.

```library(tidyverse)
primes &lt;- esieve(i)
p &lt;- length(primes)
gaps &lt;- data_frame(Gap = primes[2:p] - primes[1:(p - 1)], Sexy = Gap %% 6 == 0) %&gt;%
group_by(Gap, Sexy) %&gt;%
count()

ggplot(gaps, aes(Gap, n, fill = Sexy)) +
geom_col() +
scale_fill_manual(values = c( &quot;#7391AB&quot;, &quot;#A62102&quot;)) +
labs(title = &quot;Frequency of prime gaps for the first 10,000 primes&quot;,
x = &quot;Prime Gap&quot;,
y = &quot;Frequency&quot;)
guide_legend(title = &quot;Sexy Prime&quot;)
```

## One thought on “Euler Problem 7: 10,001st Prime and Sexy Primes”

This site uses Akismet to reduce spam. Learn how your comment data is processed.