-
Notifications
You must be signed in to change notification settings - Fork 0
/
Collatz.c++
64 lines (52 loc) · 1.1 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
// --------------------------------
// projects/c++/collatz/Collatz.c++
// Copyright (C) 2017
// Juan Trejo
// --------------------------------
// --------
// includes
// --------
#include <cassert> // assert
#include <iostream> // endl, istream, ostream
#include "Collatz.h"
using namespace std;
// ------------
// collatz_read
// ------------
int collatz_read (istream& r) {
int n;
r >> n;
assert(n > 0);
return n;}
// ------------
// collatz_eval
// ------------
int collatz_eval (long long n) {
assert(n > 0);
int m = 1;
while(n != 1){
if(n % 2 == 0){
n = n / 2;
}else{
n = n * 3 + 1;
}
m++;
}
assert(m > 0);
return m;}
// -------------
// collatz_print
// -------------
void collatz_print (ostream& w, int m) {
assert(m > 0);
w << m << endl;}
// -------------
// collatz_solve
// -------------
void collatz_solve (istream& r, ostream& w) {
int t;
r >> t;
for (int _ = 0; _ != t; ++_) {
const int n = collatz_read(r);
const int m = collatz_eval(n);
collatz_print(w, m);}}