Java を使用して約 5 分で Collatz 予想アルゴリズムを解くことができました (いいえ、証明しようとしませんでした)。
Web アプリを作成するために C# を学習しているので、同じことを行うのに問題が発生しています。ユーザーに数値を入力し、ボタンをクリックして、出力をテキストボックスに出力するだけです。
Click
私が使用しているボタンイベントハンドラーメソッドは次のとおりです。
protected void Button3_Click(object sender, EventArgs e)
{
string x = TextBox1.Text; //user entered a number
string y =collatz(x); //this function is below and returns a string
chatbox.Text = y; //output
}
コラッツ法は次のとおりです。
public static string collatz(string y)
{
if (y == null)
return null;
double x = double.Parse(y); //x is my "n"
y = x.ToString(); //output string
double large = x; //keep track of biggest number
// the algorithm
// the redundancies (like x==1.. x!= 1) are part of troubleshooting :/
while (x > 1)
{
if (x % 2 == 0)
{
x = x / 2;
if (x > large)
large = x;
if (x != 1)
y = y+" "+ x.ToString();
if (x == 1)
{
y = y + " " + x.ToString();
y = y + " largest number was " + large;
}
}
if (x % 2 != 0)
{
if (x == 1)
{
y = y+" "+ x.ToString();
y = y + " largest number was " + large;
}
x = (3 * x) + 1;
if (x > large)
large = x;
y = y+" "+ x.ToString();
}
}
return y;
}
VS.net デバッガーを使用して 2 のような数値を入力すると編集すると、出力もエラーも発生しません。私は永遠に待っているだけです。無限ループだったらそのうちエラーになるよね?
いいえ、これは宿題の問題ではありません (JAVA でやったのは 2 年前のことですが :)) 私は独学で C# を学んでいます。