[英]Finding nearest pentagonal numbers in R
Write a function in R that takes as input an integer ≥1, and returns as output the pentagonal number which is closest to s. 也就是说,你的 function 的 output 应该是满足 | -|≤| -| 对于所有正整数 m。 如果有两个这样的五边形数字,您的 function 可以返回任何一个。 通过运行 R 命令 rpois(5,lambda=800)+1 来测试您的 function 选择的五个不同的 s 值。
好的,这是我查找第 n 个五边形数的代码:
pentagonal_numbers=function(n){
sum=0
l=2*n-1
for(k in n:l){
sum=sum+k
}
return(sum)
}
那么如何找到最接近输入值的第 n 个五边形值呢?
我们可以看到查询数字的范围是有限的,所以一个简单的蛮力方法就足够了。 在这里,我们可以估计值的间隔,例如在第 10 和第 30 个数字之间。
set.seed(1)
x <- rpois(5,lambda=800)+1
f <- function(n, m){
x <- vector("integer", m[2]-m[1])
x <- (\(.) (3*.**2 - .) / 2)(m[1]:m[2])
Vectorize(function(n, x){
ind <- Position((\(f,b) \(a) f(a,b))(`>`, n), x)
x[c(ind-1, ind)] |>
(\(.).[which.min(abs(n - .))])()
}, vectorize.args = c("n"))(n, x)
}
x
#> [1] 783 838 836 812 757
f(x, c(10, 30))
#> [1] 782 852 852 782 782
请注意,这不能很好地扩展(17 秒才能找到 n < 1 000 000 的 50 000 个最接近的值)
x <- sample.int(1e6, size = 5e4, replace = T)
f(x, c(1, 850))
对于如此宽的区间,最好先构造为 hash 表,然后缩小每个数字的区间,然后匹配表。
hash_pent <- function(n){
as.list(Vectorize(\(.) (3*.**2 - .) / 2)(1:n)) |>
setNames(as.character(1:n)) |>
list2env(hash = T)
}
h <- hash_pent(10000)
和 go 从那里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.