summaryrefslogtreecommitdiff
path: root/week1/Collatz.cs
diff options
context:
space:
mode:
Diffstat (limited to 'week1/Collatz.cs')
-rw-r--r--week1/Collatz.cs25
1 files changed, 25 insertions, 0 deletions
diff --git a/week1/Collatz.cs b/week1/Collatz.cs
new file mode 100644
index 0000000..556a4c4
--- /dev/null
+++ b/week1/Collatz.cs
@@ -0,0 +1,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;
+ }
+ }
+}
+