# Exercise 3F-3 # Wondrous numbers # Start with any positive integer n. Then each term is obtained from # the previous term as follows: if the previous term is even, the next # term is one half of the previous term. If the previous term is odd, # the next term is 3 times the previous term plus 1. No matter what # value of n, the sequence will always reach 1. # Create wlengths to record the lengths of sequences wlengths<-NULL # Loop to generate the first 30 sequences for (j in 1:30) { # Set input number to change this to change the sequence wondrous<-j # No sequences are longer than 150. Start at 2 because we already have # the first term defined for (i in 2:150) { # Break out of the loop if the last number is 1 if (wondrous[length(wondrous)]==1) break # Calculate next term if (wondrous[i-1]%%2==0) { # If even, next term is (last term)/2 wondrous<-c(wondrous, wondrous[i-1]/2) } else { # If odd, next term is ((last term)*3)+1 wondrous<-c(wondrous, (wondrous[i-1]*3)+1) } } # End of i loop # Create tempcounter to record the length of the sequence # Create a new loop to count the elements in wondrous for (k in seq(wondrous)) { tempcounter<-k } # Add tempcounter to the end of wlengths wlengths<-c(wlengths,tempcounter) # Display sequence print(wondrous) } # End of j loop # Display wlengths to show the list of sequence lengths wlengths