Student number x
Student number x

Reputation: 125

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.

Upvotes: 1

Views: 188

Answers (2)

Onyambu
Onyambu

Reputation: 79338

You ca use recursion:

base3 =function(x,y=NULL){
  d = x %/% 3
  r=c(x %% 3,y)
  if(d>=3) base3(d,r)
  else c(d,r)
}
 base3(10)
[1] 1 0 1
> base3(100)
[1] 1 0 2 0 1

Upvotes: 2

Rui Barradas
Rui Barradas

Reputation: 76651

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

Upvotes: 2

Related Questions