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