Mercurial > coderloop
diff src/collatz.c @ 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.c Tue Oct 18 01:17:49 2011 -0700 1.3 @@ -0,0 +1,40 @@ 1.4 + 1.5 +#include <stdio.h> 1.6 +#include <stdlib.h> 1.7 + 1.8 +int main(int argc, char *argv[]){ 1.9 + FILE *fp; 1.10 + int n; 1.11 + if((fp=fopen(argv[1] ,"r")) == NULL) { 1.12 + printf("Cannot open file.\n"); 1.13 + exit(1);} 1.14 + fscanf(fp, "%d", &n); /* read from file */ 1.15 + int answer = search_collatz(n); 1.16 + printf("%d\n", answer); } 1.17 + 1.18 +long long collatz_next(long long n){ 1.19 + if (!(n % 2)){ 1.20 + return n/2;} 1.21 + else { 1.22 + return 1+(n*3);}} 1.23 + 1.24 +int collatz_length(int n){ 1.25 + long long t = n; 1.26 + int d = 1; 1.27 + while (t > 1){ 1.28 + t = collatz_next(t); 1.29 + d++;} 1.30 + return d;} 1.31 + 1.32 +int search_collatz(int n){ 1.33 + int max = 0; 1.34 + int max_val = 0; 1.35 + int temp_val; 1.36 + int i; 1.37 + for (i = 1; i<n; i++){ 1.38 + temp_val = collatz_length(i); 1.39 + if (temp_val > max_val){ 1.40 + max = i; 1.41 + max_val = temp_val;}} 1.42 + return max;} 1.43 +