-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path100.c
127 lines (85 loc) · 2.38 KB
/
100.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/* UVa Online Judge
* 100 - The 3n+1 Problem
* Author: Grace Chin */
#include <stdio.h>
#define DEBUG 0
unsigned int get_cycle_length( unsigned int n ) ;
int main( int argc, char* argv[] ) {
unsigned int i ; /* 0 < i < 10,000 */
unsigned int j ; /* 0 < i < 10,000 */
unsigned int n ;
unsigned int cycle_length ;
unsigned int maximum_cycle_length = 0 ;
/* Get input */
printf( "Please enter an i and a j: " ) ;
while ( scanf( "%u %u", &i, &j ) ) {
if ( DEBUG == 1 ) {
printf( "\n" ) ;
}
/* For i to j, including i and j... */
for ( n = i ; n < ( j + 1 ) ; n++ ) {
/* Get cycle length */
cycle_length = get_cycle_length( n ) ;
if ( DEBUG == 1 ) {
printf( "n is %u.\n", n ) ;
printf( "The cycle length is %u.\n", cycle_length ) ;
}
/* Update maximum cycle length */
if ( cycle_length > maximum_cycle_length ) {
maximum_cycle_length = cycle_length ;
if ( DEBUG == 1 ) {
printf( "The maxiumum cycle length has been updated to %u.\n", cycle_length ) ;
}
}
if ( DEBUG == 1 ) {
printf( "\n" ) ;
}
}
/* Print output */
printf( "%u %u %u\n", i, j, maximum_cycle_length ) ;
/* Reset maximum cycle length */
maximum_cycle_length = 0 ;
}
return 0 ;
}
unsigned int get_cycle_length( unsigned int n ) {
unsigned int cycle_length = 1 ;
if ( DEBUG == 2 ) {
printf( "\n" ) ;
}
/* Repeat as long as n is not 1... */
while ( n != 1 ) {
if ( DEBUG == 2 ) {
printf( "n is %u.\n", n ) ;
}
/* If n is odd... */
if ( n % 2 == 1 ) {
/* Multiply n by 3 and add 1. */
n = ( 3 * n ) + 1 ;
if ( DEBUG == 2 ) {
printf( "n is odd, so n has been updated to 3n+1, which is %u.\n", n ) ;
}
/* Update cycle length. */
cycle_length += 1 ;
if ( DEBUG == 2 ) {
printf( "The cycle length has been updated to %d.\n", cycle_length ) ;
}
/* If n is even... */
} else {
/* Divide n by 2. */
n = n / 2 ;
if ( DEBUG == 2 ) {
printf( "n is not odd, so n has been updated to n/2, which is %u.\n", n ) ;
}
/* Update cycle length. */
cycle_length += 1 ;
if ( DEBUG == 2 ) {
printf( "The cycle length has been updated to %u.\n", cycle_length ) ;
}
}
if ( DEBUG == 2 ) {
printf( "\n" ) ;
}
}
return cycle_length ;
}