Ok, I was recently writing a small java app that would print out values according to the Collatz Conjecture.
Collatz conjecture - Wikipedia, the free encyclopedia
Anyway, I noticed that after a certain number of iterations (i.e. the number being checked) the app just kind of sits there.
So what I did was write output to the console every 10,000 numbers.
Well, up to 100,000 it works fine. If I try it with 1,000,000, then it gets up to about 113,000 and just kinda hangs.
I'm trying to have it write out the "hailstone number" at the given position.
Here's sample output:
1 0 2 1 3 7 4 2 5 5 6 8 7 16 8 3 9 19 10 6
I also have the code below. I'm wondering if this is a variable problem, a structure problem, or if I stumbled across some kind of limit that Java has. I wrote this same app in C# and ran into the same issue.
Anyhow, here's the code (yes, I know it could probably use a good refactoring):
import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; public class HailstoneNumbers { private static Writer writer = null; public static void main(String[] args) throws IOException { long result = 0; System.out.println("Writing File."); try { writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream("C:\\hailstones.txt"), "utf-8")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } for (int x = 1; x < 1000001; x++) { if (x % 10000 == 0) { System.out.println(x + " numbers written."); } try { result = calculateHailstone(x); } catch (Exception ex) { ex.printStackTrace(); System.out.println("An error has occurred."); } writeFile(x, result); } System.out.println("File Written."); writer.flush(); writer.close(); System.in.read(); } private static long calculateHailstone(int number) { long steps = 0; if (number == 1) { steps = 0; } try { while (number != 1) { if (number % 2 == 0) { number = number / 2; } else { number = (number * 3) + 1; } steps++; } } catch (Exception ex) { ex.printStackTrace(); System.out.println("An Error has occurred."); } return steps; } private static void writeFile(int position, long hailstoneNumber) { try { writer.write(position + "\t" + hailstoneNumber + "\r\n"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Please note this is NOT a homework assignment. This was something I wrote just out of sheer curiosity.
So, does anyone have any thoughts on why this functions the way it does?? I'm striving to become a better software engineer, and I'm trying to determine here if this is something I did or didn't do (or possibly did incorrectly).
Thanks for any knowledge you may be able to pass along!