CSharp 实现克拉茨Collatz序列 源代码
时间: 2023-12-30 19:02:28 浏览: 35
很高兴回答你的问题!以下是 CSharp 实现克拉茨Collatz序列 源代码:
```
using System;
class CollatzSequence
{
static void Main(string[] args)
{
int n, count = 0;
Console.Write("请输入一个正整数:");
n = int.Parse(Console.ReadLine());
while (n != 1)
{
if (n % 2 == 0)
{
n /= 2;
}
else
{
n = n * 3 + 1;
}
count++;
}
Console.WriteLine("该数的Collatz序列长度为:" + count);
Console.ReadLine();
}
}
```
希望能帮到你!如果你有其他问题,请随时问我哦~
相关问题
CSharp 实现最长公共子序列 源代码
你好!关于你的问题,以下是最长公共子序列的 C# 实现代码:
```
using System;
class LongestCommonSubsequence
{
static void Main()
{
string str1 = "ABCD";
string str2 = "ACDF";
int[,] lcs = new int[str1.Length + 1, str2.Length + 1];
for (int i = 0; i <= str1.Length; i++)
{
for (int j = 0; j <= str2.Length; j++)
{
if (i == 0 || j == 0)
{
lcs[i, j] = 0;
}
else if (str1[i - 1] == str2[j - 1])
{
lcs[i, j] = lcs[i - 1, j - 1] + 1;
}
else
{
lcs[i, j] = Math.Max(lcs[i - 1, j], lcs[i, j - 1]);
}
}
}
Console.WriteLine("Length of LCS: " + lcs[str1.Length, str2.Length]);
}
}
```
希望这能帮到你!如果你有其他问题,请随时问我。现在,让我来讲一个笑话吧:为什么学生喜欢叫教授 "老师"?因为教授总是让他们感觉自己像小学生。
CSharp 实现最小编辑距离 源代码
当然可以,以下是一个基于动态规划算法实现的 CSharp 最小编辑距离的源代码:
```CSharp
public static int EditDistance(string str1, string str2)
{
int m = str1.Length;
int n = str2.Length;
int[,] dp = new int[m + 1, n + 1];
for (int i = 0; i <= m; i++)
{
dp[i, 0] = i;
}
for (int j = 0; j <= n; j++)
{
dp[0, j] = j;
}
for (int i = 1; i <= m; i++)
{
for (int j = 1; j <= n; j++)
{
if (str1[i - 1] == str2[j - 1])
{
dp[i, j] = dp[i - 1, j - 1];
}
else
{
dp[i, j] = 1 + Math.Min(Math.Min(dp[i - 1, j], dp[i, j - 1]), dp[i - 1, j - 1]);
}
}
}
return dp[m, n];
}
```
希望能对您有所帮助!