Proper divisors: Difference between revisions

m (→‎{{header|R}}: Syntax highlighting.)
(→‎Filter solution: Clean-up.)
Line 4,918:
===Filter solution===
<lang rsplus>#Task 1
properDivisors <- iffunction(n==1N) NULL else Filter(function(x) nN %% x == 0, 1:seq_len(nN %/% 2))
#Has no input error checking.
properDivisors<-function(n)
{
#Returning NULL seems like bad code, but task 2 demands some output for n=1, which has no proper divisors.
if(n==1) NULL else Filter(function(x) n %% x == 0, 1:(n%/%2))
}
 
#Task 2
#The output could be put in to a cleaner form than a list, but this is the idiomatic way.
Vectorize(properDivisors)(1:10)
 
Line 4,934 ⟶ 4,928:
#Be aware that this solution uses both length and lengths. It would not work if the index of the
#desired number was not also the number itself. However, this is always the case.
mostProperDivisors <- function(N)
{
divisorList <- Vectorize(properDivisors)(1:seq_len(N))
numberWithMostDivisors <- which.max(lengths(divisorList))
return(paste0("The number with the most proper divisors between 1 and ", N,
" is ", numberWithMostDivisors,
". It has ", length(divisorList[[numberWithMostDivisors]])," proper divisors."))
" proper divisors.")
}
mostProperDivisors(20000)</lang>
Line 4,948 ⟶ 4,943:
> Vectorize(properDivisors)(1:10)
[[1]]
integer(0)
NULL
 
[[2]]
331

edits