编程介的小学生 2020-01-07 00:38 采纳率: 0.4%
浏览 82

Max Factor 正确实现的方式

Problem Description
To improve the organization of his farm, Farmer John labels each of his N (1 <= N <= 5,000) cows with a distinct serial number in the range 1..20,000. Unfortunately, he is unaware that the cows interpret some serial numbers as better than others. In particular, a cow whose serial number has the highest prime factor enjoys the highest social standing among all the other cows.

(Recall that a prime number is just a number that has no divisors except for 1 and itself. The number 7 is prime while the number 6, being divisible by 2 and 3, is not).

Given a set of N (1 <= N <= 5,000) serial numbers in the range 1..20,000, determine the one that has the largest prime factor.

Input

  • Line 1: A single integer, N

  • Lines 2..N+1: The serial numbers to be tested, one per line

Output

  • Line 1: The integer with the largest prime factor. If there are more than one, output the one that appears earliest in the input file.

Sample Input
4
36
38
40
42

Sample Output
38

  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-07-26 20:05
    关注

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

    # 读取数据
    data <- readLines()
    
    # 定义函数计算最大质因数
    primeFactors <- function(n) {
      factors <- sapply(seq_along(n), function(x) {
        ifelse(n %% x == 0, x, NA)
      })
      maxPrimeFactor <- which.max(factors)
      return(maxPrimeFactor)
    }
    
    # 遍历输入序列并求解
    for(i in 1:length(data)) {
      data[i] <- strsplit(data[i], ",")[[1]][[1]]
      maxPrimeFactor <- primeFactors(data[i])
      print(paste("The largest prime factor of", data[i], "is", maxPrimeFactor))
    }
    

    这是一个简单的R程序,用于解决给定问题。首先,我们从标准输入中读取一系列的数字(这里称为"数据"),然后定义一个函数来计算每个数字的最大质因数。最后,我们遍历这些数字,并将结果打印出来。

    注意:这个程序可能无法处理非常大的数字或非常小的数字,因为它们在计算质因数时可能会导致精度丢失。对于大型数据集,您可能需要使用更复杂的算法或者优化代码以提高效率。

    评论

报告相同问题?