Write a program \"Using Mathematica\" that plots the iteration counts for each n
ID: 3890990 • Letter: W
Question
Write a program "Using Mathematica"
that plots the iteration counts for each number from 1 to a few thousand (of your choice). Some number high enough that it doesn't take forever to run but so that you get something interesting.
Begin by writing a while loop that plays the game for a single number. Once this code works, use a For loop to make your program run this while loop a number of times.
You can find the rules here:
https://en.wikipedia.org/wiki/Collatz_conjecture
The final structure of the program should look something like this:
list = {};
For[i = 1, i <= 1000, ++i,
n = i;
count = 0;
Play the Collatz game starting with n, counting the number of steps it takes to finish, use a while loop
append count to list
];
ListPlot[list];
Explanation / Answer
The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as:
while (expression) { statement(s) }
The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the whilestatement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false. Using the whilestatement to print the values from 1 through 10 can be accomplished as in the followingWhileDemo program:
class WhileDemo { public static void main(String[] args){ int count = 1; while (count < 11) { System.out.println("Count is: " + count); count++; } } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.