annotate 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
rev   line source
rlm@0 1
rlm@0 2 #include <stdio.h>
rlm@0 3 #include <stdlib.h>
rlm@0 4
rlm@0 5 int main(int argc, char *argv[]){
rlm@0 6 FILE *fp;
rlm@0 7 int n;
rlm@0 8 if((fp=fopen(argv[1] ,"r")) == NULL) {
rlm@0 9 printf("Cannot open file.\n");
rlm@0 10 exit(1);}
rlm@0 11 fscanf(fp, "%d", &n); /* read from file */
rlm@0 12 int answer = search_collatz(n);
rlm@0 13 printf("%d\n", answer); }
rlm@0 14
rlm@0 15 long long collatz_next(long long n){
rlm@0 16 if (!(n % 2)){
rlm@0 17 return n/2;}
rlm@0 18 else {
rlm@0 19 return 1+(n*3);}}
rlm@0 20
rlm@0 21 int collatz_length(int n){
rlm@0 22 long long t = n;
rlm@0 23 int d = 1;
rlm@0 24 while (t > 1){
rlm@0 25 t = collatz_next(t);
rlm@0 26 d++;}
rlm@0 27 return d;}
rlm@0 28
rlm@0 29 int search_collatz(int n){
rlm@0 30 int max = 0;
rlm@0 31 int max_val = 0;
rlm@0 32 int temp_val;
rlm@0 33 int i;
rlm@0 34 for (i = 1; i<n; i++){
rlm@0 35 temp_val = collatz_length(i);
rlm@0 36 if (temp_val > max_val){
rlm@0 37 max = i;
rlm@0 38 max_val = temp_val;}}
rlm@0 39 return max;}
rlm@0 40