Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

Need to write a specific R function - I am new to programming languages - Involving integers and vectors

The question is:

Write a function sum_mult(n,v) which takes as inputs a positive integer n and a vector of positive integers v. The output should be the sum of every number less than or equal to n, which is a multiple of at least one of the entries of v.

I am given

sum_mult(10, c(3,5)) gives [1] 33

as the result.

I started originally by writing

Integer = function(n){
   n_value = sum(0:n)
   Return(n_value)
}

I don’t know if this is taking me down the wrong path, however. Any help and guidance would be appreciated

question from:https://stackoverflow.com/questions/65852466/need-to-write-a-specific-r-function-i-am-new-to-programming-languages-involv

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Maybe you can try the code below

sum_mult <- function(n, v) sum(seq(n)[rowSums(sapply(v, function(x) seq(n) %% x) == 0) > 0])

such that

> sum_mult(5, c(2, 3))
[1] 9

> sum_mult(10, c(3, 5))
[1] 33

> sum_mult(100, c(3, 4, 5))
[1] 3046

Update if you want to count common multiples once or multiple times

sum_mult <- function(n, v) sum(sapply(v, function(x) sum(seq(n)[seq(n) %% x==0])))

Such that

> sum_mult(5, c(2, 3))
[1] 9

> sum_mult(10, c(3, 5))
[1] 33

> sum_mult(100, c(3, 4, 5))
[1] 4033

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...