as.binary <- function(n) {
	ret <- integer()
	while (n > 0) {
		m <- n %/% 2
		d <- as.integer(n - 2 * m)
		ret <- append(d, ret)
		n <- m
	}
	ret
}

ModularPower <- function(a, b, n) {
	c <- 0
	d <- 1
	for (digit in as.binary(b)) {
		c <- 2 * c
		d <- (d * d) %% n
		if (digit == 1) {
			c <- c + 1
			d <- (d * a) %%n 
		}
	}
	d
}

n <- 10383738378
a <- as.binary(n)
a
identical(sum(a * 2 ^ ((length(a) - 1) : 0)), n)
ModularPower(n, 123, 7)
