CS173: Intro to Computer Science - Iteration Revisited (3 Points)
Developed by Professor Tralie and Professor Mongan.Exercise Goals
The goals of this exercise are:- To use iteration to compute a discrete value
- To use conditionals to make choices during each loop iteration
Enter your Ursinus netid before clicking run. This is not your ID number or your email. For example, my netid is wmongan
(non Ursinus students can simply enter their name to get this to run, but they won't get an e-mail record or any form of credit).
Netid |
ThreeXPlusOne.java
public class ThreeXPlusOne {
/* Given a number x, loop until x goes to 1.
During each iteration, if x is even, divide it by 2.
If it is odd, set x to 3 times x, plus 1.
Return the number of iterations it took to solve. */
public static int threeXPlusOne(int x) {
/* TODO: Solve the three x plus one problem! */
/* hint - use a loop and an if statement! */
}
}
Driver.java
public class Driver {
public static void main(String[] args) {
int ans1 = ThreeXPlusOne.threeXPlusOne(5);
int ans2 = ThreeXPlusOne.threeXPlusOne(27);
int ans3 = ThreeXPlusOne.threeXPlusOne(17);
System.out.print(ans1 + "-" + ans2 + "-" + ans3);
}
}
Driver.main(null);
Output
Trivia
This problem is part of the Collatz Conjecture which suggests that any value will eventually converge back to 1 after a finite number of iterations. We don’t know if this is true!