Mercurial > coderloop
comparison 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 |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:307a81e46071 |
---|---|
1 package coderloop; | |
2 | |
3 import java.io.File; | |
4 import java.util.Scanner; | |
5 | |
6 class Collatz { | |
7 public static void main(String[] args)throws java.io.FileNotFoundException{ | |
8 File file = new File(args[0]); | |
9 Scanner scanner = new Scanner(file); | |
10 int n = scanner.nextInt(); | |
11 System.out.println(search_collatz(n));} | |
12 | |
13 public static long collatz_next(long n){ | |
14 if (0 == (n % 2)){ | |
15 return n/2;} | |
16 else { | |
17 return (1 + (n * 3));}} | |
18 | |
19 public static int collatz_length(int n){ | |
20 long t = n; | |
21 int d = 1; | |
22 while (t > 1){ | |
23 t = collatz_next(t); | |
24 d++;} | |
25 return d;} | |
26 | |
27 public static int search_collatz(int n){ | |
28 int max = 0; | |
29 int max_val = 0; | |
30 int temp_val = 0; | |
31 for (int i = 1; i<n; i++){ | |
32 temp_val = collatz_length(i); | |
33 if (temp_val > max_val){ | |
34 max = i; | |
35 max_val = temp_val;}} | |
36 return max;} | |
37 } |