summaryrefslogtreecommitdiff
path: root/week1/Collatz.cs
blob: 556a4c458038161f07369e5fb8c0b31c90979cc8 (plain)
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
namespace ALGA {
	public class Collatz {
		public static int collatz_recursive(int n) {
			if (n <= 0) return -1;
			if (n == 1) return 0;
			if (n % 2 == 0) n /= 2;
			else n = n * 3 + 1;
			return 1 + collatz_recursive(n);
		}

		public static int collatz_iterative(int n) {
			if (n <= 0) return -1;
			if (n == 1) return 0;

			int steps = 0;
			while (n != 1) {
				if (n % 2 == 0) n /= 2;
				else n = n * 3 + 1;
				steps++;
			}
			return steps;
		}
	}
}