Categories
Coding Project Euler R

Project Euler Problem #2 (R)

Here is a solution for Project Euler’s Problem #2 in R, which is stated as:

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …

Find the sum of all the even-valued terms in the sequence which do not exceed four million.

Firstly ,we will define a function to calculate the Fibonacci numbers below N, where N in this case is 4*10^6:

[code lang=”R”]
fib < – function(n) {
x <- c(length=10)
x[1] <- 1; x[2] <- 2
for (i in 3:n) {
y <- x[i-1]+x[i-2];
if (y > n){ break }
else { x[i] < – y }
}
x
}
[/code]

Next, we just calculate the sum of the even-valued problems, in a similar manner to the way we solved problem #1:

[code lang=”R”]
f < – fib(4E6)
sum(f[f %% 2 ==0])
[/code]

Categories
Coding Project Euler R

Project Euler Problem #1 (R)

Here is a solution for Project Euler’s problem #1 in R. The problem is expressed as:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

As usual with Project Euler questions, there is an obvious way, and a less obvious, but much more efficient way. In this case, the obvious way is:

[code lang=”R”]
x < – seq(1,999)
sum(x[x %% 3 ==0 | x %% 5 == 0])
[/code]

Which very concisely returns the correct answer, 233168. However, if we use the following intuition:

\[S_N = S_3 + S_5 – (S_{3,5})\]

i.e. the sum of all numbers divisible by 3 or 5 is the sum of all numbers divisible by 3, plus the sum of all numbers divisible by 5, minus the sum of all numbers divisible by 3 and 5 (as we have double counted them), then we get the correct answer.

Since \[S_n = \frac{n(a_1 + a_n)}{2}\], where \(n = \lfloor \frac{N}{n} \rfloor\), and \(a_n = a_1n\), the last piece of the puzzle is what to use for \(S_{3,5}\). This is straightforward, we just use the lowest common multiple of 3 and 5, which in this case is 15. Hence, the R representation of this is:

[code lang=”R”]sum(333*((3+333*3)/2),199*((5+199*5)/2)-66*((15+66*15)/2))[/code]

Categories
Coding Finance R

Black-Scholes in R

Here is a simple implementation of the Black-Scholes pricing formula in R. This will return a two-element vector containing the calculated call and put price, respectively.

[source lang=”r”]
# Black-Scholes Option Value
# Call value is returned in values[1], put in values[2]
blackscholes <- function(S, X, rf, T, sigma) {
values <- c(2)

d1 <- (log(S/X)+(rf+sigma^2/2)*T)/(sigma*sqrt(T))
d2 <- d1 – sigma * sqrt(T)

values[1] <- S*pnorm(d1) – X*exp(-rf*T)*pnorm(d2)
values[2] <- X*exp(-rf*T) * pnorm(-d2) – S*pnorm(-d1)

values
}
[/source]

Example use:

> blackscholes(100,110,.05,1,.2)
[1] 6.040088 10.675325