-
Notifications
You must be signed in to change notification settings - Fork 0
/
Collatz.c++
76 lines (64 loc) · 1.47 KB
/
Collatz.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
// ----------------------------
// projects/collatz/Collatz.c++
// Copyright (C) 2016
// Glenn P. Downing
// ----------------------------
// --------
// includes
// --------
#include <cassert> // assert
#include <iostream> // endl, istream, ostream
#include <sstream> // istringstream
#include <string> // getline, string
#include <utility> // make_pair, pair
#include "Collatz.h"
using namespace std;
// ------------
// collatz_read
// ------------
pair<int, int> collatz_read (const string& s) {
istringstream sin(s);
int i;
int j;
sin >> i >> j;
return make_pair(i, j);}
// ------------
// collatz_eval
// ------------
int collatz_eval (int i, int j) {
int ans = -1;
int count = 0;
int num;
for(int x = i; x < j; x++){
num = x;
while(num != 1){
count++;
if (num % 2 != 0){
num = 3*num + 1;
}
else{
num /= 2;
}
}
if (count > ans)
ans = count;
count = 0;
}
return ans;
}
// -------------
// collatz_print
// -------------
void collatz_print (ostream& w, int i, int j, int v) {
w << i << " " << j << " " << v << endl;}
// -------------
// collatz_solve
// -------------
void collatz_solve (istream& r, ostream& w) {
string s;
while (getline(r, s)) {
const pair<int, int> p = collatz_read(s);
const int i = p.first;
const int j = p.second;
const int v = collatz_eval(i, j);
collatz_print(w, i, j, v);}}