Skip to content

Instantly share code, notes, and snippets.

@Shreyes2010
Created January 4, 2012 12:29
Show Gist options
  • Save Shreyes2010/1559838 to your computer and use it in GitHub Desktop.
Save Shreyes2010/1559838 to your computer and use it in GitHub Desktop.
Utkarsh solution
single.call <- function(limit) { # Another cute function that returns the vector that contains the number of iterations for each number.
memo <- rep(-1, limit)
memo[1] <- 0
for(i in c(2:limit)) {
l <- 0
n <- i
while(n >= i) { # Check only so long as "n > i" and not "1" this is basically the optimization we wanted.
l <- l + 1
if(n %% 2 == 0) {
n <- n / 2
} else {
n <- 3 * n + 1
}
} # This while loop makes sure that the number is iterated only till the time it is greater than one of the previously computed number.
# In our case, (where the number is 13) this loop will run till the value after iteration reaches 10 (which has been previously computed and is stored in memo[10] think why?)
memo[i] <- memo[n] + l # This is where the magic takes place. You count the steps that took while iterating 13 -> 40 -> 20 -> 10 (that is 4, this is "l") and then just add it to memo[10] (which contains the number of iteration that are needed to go from 10 to 1)
}
return(memo)
}
system.time(temp <- single.call(1000000)) # Now do this for 1,000,000 (instead of 13)
which(temp == max(temp)) # Which number has the maximum iterations
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment