# The Ulam Spiral: Euler Problem 28

Euler Problem 28 takes us to the world of the Ulam Spiral. This is a spiral that contains sequential positive integers in a square spiral, marking the prime numbers. Stanislaw Ulam discovered that a lot of primes are located along the diagonals. These diagonals can be described as polynomials. The Ulam Spiral is thus a way of generating quadratic primes (Euler Problem 27).

Ulam Spiral (WikiMedia).

## Euler Problem 28 Definition

Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:

21 22 23 24 25
20 07 08 09 10
19 06 01 02 11
18 05 04 03 12
17 16 15 14 13

It can be verified that the sum of the numbers on the diagonals is 101. What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?

## Proposed Solution

To solve this problem we do not need to create a matrix. This code calculates the values of the corners of a matrix with size $n$. The lowest number in the matrix with size $n$ is $n(n-3)+4$. The numbers increase by $n-1$.

The code steps through all matrices from size 3 to 1001. The solution uses only the uneven sized matrices because these have a centre. The answer to the problem is the sum of all numbers.

size <- 1001 # Size of matrix
answer <- 1 # Starting number
# Define corners of subsequent matrices
for (n in seq(from = 3, to = size, by = 2)) {
corners <- seq(from = n * (n - 3) + 3, by = n - 1, length.out = 4)
}


## Plotting the Ulam Spiral

We can go beyond Euler Problem 28 and play with the mathematics. This code snippet plots all the prime numbers in the Ulam Spiral. Watch the video for an explanation of the patterns that appear along the diagonals.

Ulam Spiral prime numbers.

The code creates a matrix of the required size and fills it with the Ulam Spiral. The code then identifies all primes using the is.prime function from Euler Problem 7. A heat map visualises the results.

# Ulam Spiral
size <- 201 # Size of matrix
ulam <- matrix(ncol = size, nrow = size)
mid <- floor(size / 2 + 1)
ulam[mid, mid] <- 1
for (n in seq(from = 3, to = size, by = 2)) {
numbers <- (n * (n - 4) + 5) : ((n + 2) * ((n + 2) - 4) + 4)
d <- mid - floor(n / 2)
l <- length(numbers)
ulam[d, d:(d + n - 1)] <- numbers[(l - n + 1):l]
ulam[d + n - 1, (d + n - 1):d] <- numbers[(n - 1):(n - 2 + n)]
ulam[(d + 1):(d + n - 2), d] <- numbers[(l - n):(l - 2 * n + 3)]
ulam[(d + 1):(d + n - 2), d + n - 1] <- numbers[1:(n - 2)]
}
ulam.primes &lt;- apply(ulam, c(1, 2), is.prime)

# Visualise
library(ggplot2)
library(reshape2)
ulam.primes <- melt(ulam.primes)
ggplot(ulam.primes, aes(x=Var1, y=Var2, fill=value)) + geom_tile() +
scale_fill_manual(values = c("white", "black")) +
guides(fill=FALSE) +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank()) +
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank(),
axis.title.y=element_blank(),
axis.text.y=element_blank(),
axis.ticks.y=element_blank()
)


# Generating Quadratic Primes: Euler Problem 27

Prime numbers are the engine of the Internet economy. One of the reasons prime numbers are so useful is that they cannot be generated through an algorithm. This impossibility has not stopped mathematicians from trying to find formulas to generate prime numbers.

Euler problem 27 deals with quadratic formulas that can be used to generate sets of prime numbers. We have already discussed this in the post about the Ulam Spiral. This Numerphile video discusses quadratic primes.

## Euler Problem 27 Definition

Euler discovered the remarkable quadratic formula:

$n^2+n+41$

It turns out that the formula will produce $40$ primes for the consecutive integer values $0 \leq n \leq 39$. However, when $n=40$, $40^2+40+41=40(40+1)+41$ is divisible by $41$, and certainly when $n=41$, $41^2+41+41$ is clearly divisible by $41$.

The incredible formula $n^2-79n+1601$ was discovered, which produces 80 primes for the consecutive values $0 \leq n \leq 79$. The product of the coefficients, $-79$ and $1601$, is $-126479$.

Considering quadratics of the form: $n^2+an+bn^2+an+b$,

where $|a| < 1000$ and $|b| \leq 1000$, where $|n|$ is the modulus/absolute value of $n$, e.g. $|11|=11$ and $|-4|=4$.

Find the product of the coefficients, $a$ and $b$, for the quadratic expression that produces the maximum number of primes for consecutive values of $n$, starting with $n=0$.

## Proposed Solution

The only way to solve this problem is through brute force and reduce the solution space to optimise it for speed (source: mathblog.dk). Because the outcome of the equation must be prime for $n = 0$, $b$ also has to be prime. We can use the prime sieve from Euler Problem 3, which reduces it from 2000 to 168 options. When we insert $n = 1$ it follows that a has to be an even number. If $1+a+b$ has to be prime and $b$ has to be a prime number, then a can only be an odd number. However, when $b = 2$, a has to be even.

## Euler Problem 27 code

seq.a <- seq(-999, 1001, 2) # a has to be odd
seq.b <- (esieve(1000)) # b has to be prime
max.count <- 0
for (a in seq.a) {
if (a == 2)
seq.a <- seq(-1000, 1000, 2) # a has to be even
for (b in seq.b) {
n <- 0 # Find sequence of primes for a and b
while (is.prime(n^2 + a * n + b)) {
n <- n + 1 } # Store maximum values if (n > max.count) {
max.count <- n
max.a <- a
max.b <- b
}
}
}


# Euler Problem 12: Highly Divisible Triangular Number

The divisors of 10 illustrated with Cuisenaire rods: 1, 2, 5, and 10 (Wikipedia).

Euler Problem 12 takes us to the realm of triangular numbers and proper divisors.

The image on the left shows a hands-on method to visualise the number of divisors of an integer. Cuisenaire rods are learning aids that provide a hands-on way to explore mathematics.

## Euler Problem 12 Definition

The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be $1 + 2 + 3 + 4 + 5 + 6 + 7 = 28$. The first ten terms would be: $1, 3, 6, 10, 15, 21, 28, 36, 45, 55, \ldots$ Let us list the factors of the first seven triangle numbers:

1: 1

3: 1, 3

6: 1, 2, 3, 6

10: 1, 2, 5, 10

15: 1, 3, 5, 15

21: 1, 3, 7 ,21

28: 1, 2, 4, 7, 14, 28

We can see that 28 is the first triangle number to have over five divisors. What is the value of the first triangle number to have over five hundred divisors?

## Solution

Vishal Kataria explains a simple method to determine the number of divisors using prime factorization as explained by in his video below. The prime factorization of $n$ is given by:

$n = p^{\alpha_1}_1 \times p^{\alpha_2}_2 \times p^{\alpha_k}_k$

The number of proper divisors is:

$d = (\alpha_1 + 1) (\alpha_2 + 1) \ldots (\alpha_k + 1)$

The code reuses the prime factorisation function developed for Euler Problem 3. This function results in a vector of all prime factors, e.g. the prime factors of 28 are 2, 2 and 7.

The code to solve this problem determines the values for alpha using the run length function. This function counts the number of times each element in a sequence is repeated. The outcome of this function is a vector of the values and the number of times each is repeated. The prime factors of 28 are 2 and 7 and their run lengths are 2 and 1. The number of divisors can now be determined.

$28 = 2^2 \times 7^1$

$d = (2+1)(1+1) = 6$

The code to solve Euler Problem 12 is shown below. The loop continues until it finds a triangular number with 500 divisors. The first two lines increment the index and create the next triangular number. The third line in the loop determines the number of times each factor is repeated (the run lengths). The last line calculates the number of divisors using the above-mentioned formula.

i <- 0
divisors <- 0
while (divisors < 500) {
i <- i + 1
triangle <- (i * (i+1)) / 2
pf <- prime.factors(triangle)
alpha <- rle(pf)
divisors <- prod(alpha\$lengths+1)
}


View the code on GitHub.

# Euler Problem 10: Summation of Primes

Euler Problem 10 asks for the summation of primes. Computationally this is a simple problem because we can re-use the prime sieve developed for problem 3.

When generating a large number of primes the erratic pattern at which they occur is much more interesting than their sum. Mathematicians consider primes the basic building blocks of number theory. No matter how hard we look, however, they do not seem to obey any logical sequence. This Euler Problem is simply

## Euler Problem 10 Definition

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million.

## Solution

The sieve of Eratosthenes function used in Euler Problem 3 can be reused once again to generate the prime numbers between two and two million. An interesting problem occurs when I run the code. When I sum all the primes without the as.numeric conversion, R throws an integer overflow error and recommends the conversion.

primes <- esieve(2e6)


This results in a vector containing the first 148,933 prime numbers. The largest prime gap is 132 and it seems that sexy primes are more common than any of the other twin primes (note the spikes at intervals of 6 in the bar chart).

You can view the code on GitHub.

## Goldbach’s Conjecture

The summing of primes reveals an interesting problem in mathematics. Goldbach’s conjecture is one of the oldest and best-known unsolved problems in number theory and states that:

Every even integer greater than 2 can be expressed as the sum of two primes.

Note that this conjecture is only about even numbers. Goldbach also theorised that every odd composite number can be written as the sum of a prime and twice a square. This conjecture is the subject of the Euler Problem 46, which I will work on soon.

# 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 can be reused to generate 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.

is.prime <- function(n) {
primes <- esieve(ceiling(sqrt(n)))
prod(n%%primes!=0)==1
}

i <- 2 # First Prime
n <- 1 # Start counter
while (n<10001) { # Find 10001 prime numbers
i <- i + 1 # Next number
if(is.prime(i)) { # Test next number
n <- n + 1 # Increment counter
i <- i + 1 # Next prime is at least two away
}
}



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.

You can also view this code on GitHub.

Prime gap frequency distribution for the first 10001 primes.

# Euler Problem 3: Largest Prime Factor

## Euler Problem 3 Definition

The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143?

## Generating Prime Numbers

This solution relies on two functions that can be used for multiples problems. The Sieve of Eratosthenes generates prime numbers from 2 to n. The code is commented to explain the sieve and the image shows how numbers from 1 to 100 are sieved to find the primes.

Sieve of Eratosthenes. Green are multiples of 2, Blue are multiples of 3, the orange coloured numbers are multiples of 5 and purple the multiples of 7. The remaining numbers (except 1) are the prime numbers (black).

The prime.factors function generates the list of unique prime divisors and then generates the factors. The factors are identified by dividing the number by the candidate prime factors until the result is 1.

## Solution

# Sieve of Eratosthenes for generating primes 2:n
esieve <- function(n) {
if (n==1) return(NULL)
if (n==2) return(n)
# Create a list of consecutive integers {2,3,…,N}.
l <- 2:n
# Start counter
i <- 1
# Select p as the first prime number in the list, p=2.
p <- 2
while (p^2<=n) {
# Remove all multiples of p from the l.
l <- l[l == p | l %% p!= 0]
# set p equal to the next integer in l which has not been removed.
i <- i + 1 # Repeat steps 3 and 4 until p2 > n, all the remaining numbers in the list are primes
p <- l[i]
}
return(l)
}

# Prime Factors
prime.factors <- function (n) {
factors <- c() # Define list of factors
primes <- esieve(floor(sqrt(n))) # Define primes to be tested
d <- which(n%%primes == 0) # Idenitfy prime divisors
if (length(d) == 0) # No prime divisors
return(n)
for (q in primes[d]) { # Test candidate primes
while (n %% q == 0) { # Generate list of factors
factors <- c(factors, q)
n <- n/q } } if (n > 1) factors <- c(factors, n)
return(factors)
}

max(prime.factors(600851475143))


The solution can also be found by using the primeFactors function in the numbers package. This package provides a range of functions related to prime numbers and is much faster than the basic code provided above.

library(numbers)
max(primeFactors(600851475143))


This code on GitHub.