-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathCollatz.cs
45 lines (41 loc) · 1.08 KB
/
Collatz.cs
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
using System;
class Collatz{
static void Main(string[] args){
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("<--------------Collatz--------------->");
Console.WriteLine("Created by Morasiu (morasiu2@gmail.com)");
Start();
}
static void Start(){
int num = GetNumber();
CollatzConjecture(num);
Console.Write("\b\n");
}
static int CollatzConjecture(int num){
/*Consider the following operation on an arbitrary positive integer:
If the number is even, divide it by two.
If the number is odd, triple it and add one.*/
Console.Write(num + ",");
if(num == 1)
return 1;
else if(num % 2 == 0){
return CollatzConjecture(num/2);
} else {
return CollatzConjecture(3*num + 1);
}
}
static int GetNumber(){
int num = 0;
while (true){
Console.Write("Enter starting number: ");
string sNum = Console.ReadLine();
try{
num = int.Parse(sNum);
if(num > 0)
break;
} catch {}
Console.WriteLine("Wrong number");
}
return num;
}
}