【问题标题】:Algorithm that gives you any number n in base 10 in base 3以 3 为底的以 10 为底的任意数字 n 的算法
【发布时间】:2018-03-09 17:41:26
【问题描述】:

我需要编写一个算法,在 R 中为您提供以 3 为底的任意数字 n。到目前为止,我写的是:

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)}

我认为通过应用 sapply(vector, ternary),对于任何给定的 n,它都会给我所有的 r,我将在 ternary(n) 中放入。我的代码仍然给了我“最后一个 r”,我不明白为什么。

【问题讨论】:

  • 当你输入 10 时你期望的结果是什么?
  • 我希望输出为 (1,0,1) 作为向量。

标签: r algorithm base


【解决方案1】:

这是我在 n 年级时学会的手工操作的简单实现(不记得确切的时间)。

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

【讨论】:

    【解决方案2】:

    你可以使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-18
      • 1970-01-01
      • 1970-01-01
      • 2022-12-07
      • 2020-12-29
      • 2014-09-29
      • 1970-01-01
      相关资源
      最近更新 更多