CS173: Intro to Computer Science - Iteration Revisited (3 Points)

Developed by Professor Tralie and Professor Mongan.

Exercise Goals

The goals of this exercise are:
  1. To use iteration to compute a discrete value
  2. To use conditionals to make choices during each loop iteration
Modify the ThreeXPlusOne.java file to solve the 3x+1 problem using a loop and conditional.

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).

Clicking Run below will check your work and, if it passes, will submit your work automatically. You must be connected to the VPN for submission to be successful! You will receive a copy of your code via e-mail, so you'll know that it was submitted if you receive that e-mail! VPN access requires Multi-Factor Authentication, which sends you a code when you log into the network. Instructions on configuring these for your account can be found here.


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! */ } }


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); } }



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!