Skip to content

Instantly share code, notes, and snippets.

@sebfischer83
Created June 13, 2017 07:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebfischer83/a7d1af378b51649670569ca5a3d57c32 to your computer and use it in GitHub Desktop.
Save sebfischer83/a7d1af378b51649670569ca5a3d57c32 to your computer and use it in GitHub Desktop.
collatz
public static string collatz(string input)
{
int current = 0;
if (string.IsNullOrEmpty(input) || !int.TryParse(input, out current) || current < 1) {
return "Empty, not a number or less then 1";
}
int max = current;
while (current > 1) {
if (current % 2 == 0) {
current = current / 2; // current reassigned
if (current > max)
max = current;
if (current != 1)
input = input + " " + current.ToString();
if (current == 1) {
input = input + " " + current.ToString();
input = input + " largest number was " + max;
}
} else {
if (current == 1) {
input = input + " " + current.ToString();
input = input + " largest number was " + max;
}
current = (3 * current) + 1;
if (current > max)
max = current;
input = input + " " + current.ToString();
}
}
return input;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment