ContainsF、质数分解、计算最大公约数

This commit is contained in:
龙腾猫跃 committed 2026-07-09 19:07:53 +08:00
1 parent 7bc61645d5
commit 86263b0b75
2 files changed
+47

No files matched your search

+6
View File
@@ -37,6 +37,12 @@ public static class StringExtensions {
public static bool ContainsIgnoreCase(this string value, string subString)
=> value.IndexOf(subString, StringComparison.OrdinalIgnoreCase) >= 0;
/// <summary>
/// 非区域性的 <see cref="string.Contains(string)"/>。
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool ContainsF(this string? value, string subString, bool ignoreCase = false)
=> value?.IndexOf(subString, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) >= 0;
/// <summary>
/// 非区域性的 <see cref="string.IndexOf(string)"/>。
+41
View File
@@ -109,4 +109,45 @@ public static class MathUtils {
return 3 * a * ((0.33333333 + y1 - y2) * a * a + (y2 - 2 * y1) * a + y1);
}
/// <summary>
/// 对质数进行分解。
/// </summary>
public static IEnumerable<int> GetPrimeFactors(int num) {
num = Math.Abs(num);
while (num % 2 == 0 && num > 1) {
yield return 2;
num /= 2;
}
int i = 3;
int maxFactor = (int) Math.Sqrt(num);
while (i <= maxFactor) {
while (num % i == 0) {
yield return i;
num /= i;
maxFactor = (int) Math.Sqrt(num);
}
i += 2;
}
if (num > 2) yield return num;
}
/// <summary>
/// 计算最大公约数。例如 12 和 16 的结果是 4。
/// </summary>
public static int Gcd(int a, int b) {
a = Math.Abs(a);
b = Math.Abs(b);
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
/// <summary>
/// 计算最大公约数。例如 12 和 16 的结果是 4。
/// </summary>
public static int Gcd(double a, int b)
=> Gcd((int) Math.Round(a), b);
}