I want to write a program witch has something to do with 3x+1, but that's not important. First it has to figure out if the given number is odd or even. This is done via switch statement:
switch(input % 2)
{
case 0: //even
input = input / 2;
count++;
break;
case 1: //uneven
input = 3 * input + 1;
count++;
break;
}
if(input == 1)
{
System.out.println("reached 4, 2, 1 loop.\nTook " + count + " steps.");
return;
}
tryNumber(input);
Even numbers are divided by 2, uneven/odd ones are multiplied by 3 and incremented by 1.
So the problem is that it prints numbers which are completely wrong, for example using 2:
Please put in a number:
2
50
25
76
38
19
58
29
88
44
22
11
34
17
52
26
13
40
20
10
5
16
8
4
2
reached 4, 2, 1 loop.
Took 24 steps.
Where is the mistake? Thanks for any replies.
whole code:
package de.craftingdani.math.main;
import java.io.IOException;
public class Main
{
static long count = 0;
public static void main(String[] args)
{
try
{
System.out.println("Please put in a number: ");
tryNumber(System.in.read());
}
catch(Exception e)
{
System.err.println(" Error, please give a valid number");
e.printStackTrace();
}
}
public static void tryNumber(int input) throws InterruptedException, IOException
{
Thread.sleep(100);
System.out.println(input);
switch(input % 2)
{
case 0: //even
input = input / 2;
count++;
break;
case 1: //odd
input = 3 * input + 1;
count++;
break;
}
if(input == 1)
{
System.out.println("reached 4, 2, 1 loop.\nTook " + count + " steps.");
return;
}
tryNumber(input);
}
}