编程介的小学生 2019-08-30 23:56 采纳率: 0.4%
浏览 89

数组的复杂问题 ACM(Array Complicated Manipulation)

Problem Description
Given an infinite array of integers 2,3,.... Now do some operations on it.

The operation is to choose a minimum number from the array which is never been chosen, then change the status of its multiples excluding itself, i.e remove the multiples of the chosen number if they are in the array , otherwise add it to the array.keep the order after change.

For instance, the first step, choose number 2, change the status of 4, 6, 8, 10... They are all removed from the array. The second step, choose 3, change the status of 6, 9, 12, 15...

Pay attention: 9 and 15 are removed from the array while 6 and 12 are added to the array.

Input
Every line contains an integer n. The zero value for n indicates the end of input.

Output
Print "yes" or "no" according whether n is in the array.

Sample Input
2
30
90
0

Sample Output
yes
yes
no

  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-07-31 02:51
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    # read data
    data <- readLines()
    
    # initialize result list
    res <- c("yes", "yes")
    
    # iterate through each line
    for (i in 2:length(data)) {
      # get current line's integer value
      val <- as.integer(substr(data[i], 1, -1))
      
      # check if val exists in res
      if (!any(res == val)) {
        # find all multiples of val that are not in res
        mults <- unique(which(val %in% data) %in% res & !val %in% res)
        
        # remove those multiples from res
        res[!mults] <- ""
        
        # add new multiples to res
        res <- paste(c(res, paste(mults)), collapse = ", ")
      }
    }
    
    # print result
    print(res)
    
    评论

报告相同问题?