Categories
Coding Project Euler R

Project Euler Problem #21

This is a solution for problem 21 on the Project Euler website. It consists of finding the sum of all the amicable numbers under 10000. This was pretty easy to solve, but the solution could probably be improved quite a bit.

Solution #1 in R is as follows (it calculates the proper divisors of each number using prop.divs, and then adds up the sequence of amicable numbers in the main function).

[sourcecode language=”matlab”]
prop.divs <- function(x) {
if (x == 1) return (1)
divs <- integer(30)
j <- 1
divs[j] <- 1
j <- j + 1
for (i in 2:(floor(x/2))) {
if ((x %% i) == 0) {
divs[j] <- i
j <- j + 1
}
}
sum(divs[1:(j-1)])
}

problem.21 <- function(N) {
s <- 0
for (i in 2:N) {
da <- prop.divs(i)
if (da == i) next
db <- prop.divs(da)
if ( db==i ) {
s <- s + da + db
}
}
s/2
}
[/sourcecode]

The s/2 is needed as each factor is added twice during the calculation.

This gives the correct answer, but the implementation is a bit naive. I remembered coming across an article about prime factors and proper divisors on PlanetMath a while ago, and this seemed like potentially a more efficient way to calculate the factors involved. Specifically, the sum of proper divisors of a number n can be given by:

\[ \prod_{i=1}^k\frac{p_i^{m_i+1}-1}{p_i – 1}-\prod_{i=1}^kp_i^{m_i} \]

The second attempt at this problem looked like the following:

[sourcecode language=”r”]
prime.sieve <- function(n) {
a <- seq.int(1,n)
p <- 1
M <- as.integer(sqrt(n))
while ((p <- p + 1) <= M) {
if (a[p] != 0)
a[seq.int(p*p, n, p)] <- 0
}
a[a>1 & a>0]
}

sum.proper.divisors <- function(x) {
primes <- prime.sieve( x )
primes <- primes[ x %% primes == 0]

geo.sum <- numeric(length(primes))
i <- 1

for (prime in primes) {
n <- x
curr <- 0
while (n %% prime == 0) {
curr <- curr + 1
n <- n %/% prime
}
geo.sum[i] <- ( (prime^(curr+1) – 1)/(prime – 1) )
i <- i + 1
}
prod(geo.sum)-x
}

problem.21_2 <- function(N) {
s <- 0
for (i in 2:N) {
da <- sum.proper.divisors(i)
if (da == i) next
db <- sum.proper.divisors(da)
if (db==i) s <- s + da +db
}
s/2
}
[/sourcecode]

This also gives the correct answer, but with much reduced runtime overhead:


> system.time(problem.21(10000))
user system elapsed
103.943 0.511 106.978
> system.time(problem.21_2(10000))
user system elapsed
24.834 0.160 26.565

Categories
Coding R

Headless R / X11 and Cygwin/X

Running R on a Linux server in headless mode (i.e. producing graphics without XWindows running) can be tricky. Some people recommend using a virtual X framebuffer. However, I’ve found that the best approach (at least im my opinion) is to use the R interface to Cairo. This allows R to produce png graphics in headless mode, and also produces very nice looking graphs. I configured R as follows (after downloading and building pixman-0.15.18, and cairo-1.8.8:

./configure --with-gnu-ld --with-x --with-cairo

This will produce an R binary with cairo support that can be run non-interactively and produce graphical output – very useful for running automated statistical reports.

You can check that Cairo support is enabled by checking the return value of the capabilities() function:

> capabilities()
jpeg png tiff tcltk X11 aqua http/ftp sockets
TRUE TRUE FALSE FALSE FALSE FALSE TRUE TRUE
libxml fifo cledit iconv NLS profmem cairo
TRUE TRUE TRUE TRUE TRUE FALSE TRUE

Finally, some notes on connecting X11 clients using Cygwin (which I always forget how to do). On the server, check /etc/ssh/sshd_config for the line

X11Forwarding yes

And then run a local X server:

XWin -clipboard -emulate3buttons -multiwindow

Once this is running, from an xterm, run ssh, passing in the -X argument to enable X forwarding.

ssh -X -l username myserver

X11-based applications can then be run from this session.

Categories
Coding kdb R

Compiling The kdb/R interface on Win32

I have been playing with the kdb/R interface from kx.com, and had some problems installing with Cygwin gcc. It may be possible to get this to work with Cygwin gcc + a Win32 threads library, but in the meantime I installed MinGW, and it works perfectly. Here are the steps (basically as per the kx docs):

1. Download c.o from here: http://kx.com/q/w32/
2. gcc -c base.c -I. -I "${R_HOME}/include/"
3. gcc -Wl,--export-all-symbols -shared -o qserver.dll c.o base.o ${r
-HOME}/bin/R.dll -lws2_32

The resulting qserver.dll can be loaded via dyn.load(), and then (just using the qserver.R supplied by kx) from within R:

source("qserver.R")
conn < - open_connection("server", 12345) result <- execute(conn, "select avg bid by sym from fx_quote") x <- as.data.frame(mapply(FUN=c, result)) > head(x, 10)
V1 V2
1 AUD= 0.792402880224811
2 AUD=D2 0.791632149468651
3 AUD=EBS 0.790402776387278
4 AUDCHF=R 0.85955071021153
5 AUDJPY=R 75.0707755671935
6 BRL= 1.97194091379422
7 CAD= 1.15980648929715
8 CAD=D2 1.15962545479939
9 CAD=EBS 1.14104373919176
10 CADJPY=R 81.6389284332255