CSharp 最小公倍数 源代码
时间: 2023-10-23 07:08:46 浏览: 40
以下是 C# 中求最小公倍数的源代码:
```
using System;
class LCM
{
static int GetLCM(int a, int b)
{
int max = a > b ? a : b;
int min = a < b ? a : b;
for (int i = max; ; i += max)
{
if (i % min == 0)
return i;
}
}
static void Main()
{
int a = 24;
int b = 36;
int lcm = GetLCM(a, b);
Console.WriteLine("The LCM of {0} and {1} is {2}", a, b, lcm);
}
}
```
在这个示例中,我们定义了一个 GetLCM 函数,该函数接受两个整数 a 和 b,并返回它们的最小公倍数。我们使用一个 for 循环来计算最小公倍数。我们从较大的数字开始,每次增加较大数字的值,直到它的倍数等于较小数字。在这个点上,我们可以确定找到了最小公倍数,并将其作为函数的返回值。
在主函数中,我们定义了两个整数 a 和 b,并调用 GetLCM 函数来计算它们的最小公倍数。最后,我们输出最小公倍数的值。
相关问题
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];
}
```
希望能对您有所帮助!
CSharp 实现kadane算法 源代码
当然可以,以下是CSharp实现Kadane算法的源代码:
```
using System;
class KadaneAlgorithm {
static int MaxSubArraySum(int[] arr) {
int max_so_far = arr[0];
int curr_max = arr[0];
for (int i = 1; i < arr.Length; i++) {
curr_max = Math.Max(arr[i], curr_max + arr[i]);
max_so_far = Math.Max(max_so_far, curr_max);
}
return max_so_far;
}
static void Main() {
int[] arr = {-2, -3, 4, -1, -2, 1, 5, -3};
int max_sum = MaxSubArraySum(arr);
Console.WriteLine("Maximum contiguous sum is " + max_sum);
}
}
```
希望能对你有所帮助!现在轮到你了,你能讲一个好笑的笑话吗?