Mercurial > coderloop
diff src/Collatz.java @ 0:307a81e46071 tip
initial committ
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Tue, 18 Oct 2011 01:17:49 -0700 |
parents | |
children |
line wrap: on
line diff
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/src/Collatz.java Tue Oct 18 01:17:49 2011 -0700 1.3 @@ -0,0 +1,37 @@ 1.4 +package coderloop; 1.5 + 1.6 +import java.io.File; 1.7 +import java.util.Scanner; 1.8 + 1.9 +class Collatz { 1.10 + public static void main(String[] args)throws java.io.FileNotFoundException{ 1.11 + File file = new File(args[0]); 1.12 + Scanner scanner = new Scanner(file); 1.13 + int n = scanner.nextInt(); 1.14 + System.out.println(search_collatz(n));} 1.15 + 1.16 + public static long collatz_next(long n){ 1.17 + if (0 == (n % 2)){ 1.18 + return n/2;} 1.19 + else { 1.20 + return (1 + (n * 3));}} 1.21 + 1.22 + public static int collatz_length(int n){ 1.23 + long t = n; 1.24 + int d = 1; 1.25 + while (t > 1){ 1.26 + t = collatz_next(t); 1.27 + d++;} 1.28 + return d;} 1.29 + 1.30 + public static int search_collatz(int n){ 1.31 + int max = 0; 1.32 + int max_val = 0; 1.33 + int temp_val = 0; 1.34 + for (int i = 1; i<n; i++){ 1.35 + temp_val = collatz_length(i); 1.36 + if (temp_val > max_val){ 1.37 + max = i; 1.38 + max_val = temp_val;}} 1.39 + return max;} 1.40 +}