Search code examples
ralgorithmradix

Algorithm that gives you any number n in base 10 in base 3


I need to write an algorithm that gives you any number n in base 3 in R. So far I wrote that :

vector <- c(10, 100, 1000, 10000)

ternary <- function(n) { while (n != 0) {

  {q<- n%/%3}

  {r <- n%%3}

  {return(r)}

  q<- n  } 

sapply(vector, ternary)}

I thought that by applying sapply( vector, ternary) it would give me all the r for any given n that I would put in ternary(n). My code still gives me the "last r" and I don't get why.


Solution

  • This is the straightforward implementation of what I have learned to do by hand in nth grade (don't remember exactly when).

    base3 <- function(x){
        y <- integer(0)
        while(x >= 3){
            r <- x %% 3
            x <- x %/% 3
            y <- c(r, y)
        }
        y <- c(x, y)
        y
    }
    
    base3(10)
    #[1] 1 0 1
    
    base3(5)
    #[1] 1 2