I try to write a recursive function that returns the sum of digits. However, the program below doesn't seem to do the trick.
getSum = function(i) {
if (i < 0) {Print("Please enter a positive number")}
if (i >= 0) {getSum(i - floor(i / 10) - i %% 10) + floor(i / 10) + i %% 10}
It gives two errors:
Error: evaluation nested too deeply: infinite recursion / options(expressions=)?
Error during wrapup: evaluation nested too deeply: infinite recursion /
options(expressions=)?
What can I do to solve this?
Use this
if (i >= 0)
{sum(sapply(strsplit(as.character(i),""),as.numeric))}
Of course this works for whole numbers. If your need is greater more regex can be added to accommodate that
Edited! Oops totally missed that you want a recursive function
Do you want something like this?
getSum = function(i){
i = abs(floor(i))
if (nchar(i) == 1){
return(i)
} else {
getSum(floor(i/10)) +i%%10 #Minorpt (suggested by @DashingQuark)
}
}
In R, it is recommended to use Recall
for creating a recursive function.
I am using @db's function, but demonstrating with Recall
getSum = function( i )
{
if (nchar(i) == 1){
return(i)
} else if (i < 0 ) {
"Please enter a positive number"
}else {
print(i)
Recall( i = floor(i/10)) +i%%10
}
}
getSum(0)
# [1] 0
getSum(1)
# [1] 1
getSum(-1)
# [1] "Please enter a positive number"
getSum(5)
# [1] 5
getSum(100)
# [1] 100
# [1] 10
# [1] 1
getSum( 23)
# [1] 23
# [1] 5
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.