美文网首页
和果子一起来做题-Project Euler-04-R语言版本

和果子一起来做题-Project Euler-04-R语言版本

作者: 9d760c7ce737 | 来源:发表于2017-11-23 16:45 被阅读50次

    第4题

    A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
    Find the largest palindrome made from the product of two 3-digit numbers.

    意思是找出两个三位数乘积的最大回文数。
    最朴素的思路:写一个能判断回文数的函数,把三位数的乘积全部求出,一个个判断是否是回文数,再求最大数。
    1.首先我们创建一个函数来判断回文数

    if.palin <- function(x){
      a <- as.character(x)
      b <- unlist(strsplit(a,""))
      if (all(b==b[length(b):1])) return (TRUE)
      else return(FALSE)
    }
    

    2.穷尽所有的三位数乘三位数的乘积

    g <- 0
    palin <- c()
    for (i in 100:999){
      for (j in 100:999){
        if (if.palin(i*j)==TRUE){
          g <- g +1
          palin[g] <- i*j
        }
      }
    }
    

    3.找出最大的回文数
    max(palin)

    906609

    4.如果想知道每个回文数是由哪两个数组成的怎么办?
    改写一下代码,每次把结果存入列表中

    g <- 0
    palin <- list()
    for (i in 100:999){
      for (j in 100:999){
        if (if.palin(i*j)==TRUE){
          g <- g +1
          palin[g] <- list(c(i*j,i,j))
        }
      }
    }
    

    获取列表中每个列表的第一个数,注意"[["在这个时候代表的是函数,表示获取

    all <- sapply(palin,"[[",1)
    max(all)
    

    得到906609,根据这个数值获取位置

    which(all ==906609)
    [1] 2367 2468

    有两个位置,这个情况是由之前的循环导致的,应该是一样的结果,只是顺序对调。

    palin[2367]
    [[1]]
    [1] 906609 913 993

    最终最大的回文数是906609,由913乘以993得到
    note:
    1.本次练习开始写函数,参考资料为Advanced R 第二版,但是这函数只能起到判断的作用。
    2.rev()函数可以实现向量倒序,代替b[length(b):1])) = rev(b)
    3.切开字符串使用strsplit,如果在拼回去需要用paste

    paste(c("B","S"),collapse = "")
    [1] "BS"

    相关文章

      网友评论

          本文标题:和果子一起来做题-Project Euler-04-R语言版本

          本文链接:https://www.haomeiwen.com/subject/ajnzvxtx.html