diff --git a/trick/greatest-common-divisor.cpp b/trick/greatest-common-divisor.cpp index e69de29..db0280b 100644 --- a/trick/greatest-common-divisor.cpp +++ b/trick/greatest-common-divisor.cpp @@ -0,0 +1,8 @@ +int greatest_common_divisor(int num1, int num2) { + while (num2 != 0) { + int temp = num2; + num2 = num1 % num2; + num1 = temp; + } + return num1; +} \ No newline at end of file diff --git a/trick/knuth-morris-pratt.cpp b/trick/knuth-morris-pratt.cpp index e69de29..0f477db 100644 --- a/trick/knuth-morris-pratt.cpp +++ b/trick/knuth-morris-pratt.cpp @@ -0,0 +1,29 @@ +#include +#include + +int knuth_morris_pratt(const std::string text, const std::string pattern) { + int n = text.length(), m = pattern.length(); + std::vector next(m, 0); + for (int i = 1, j = 0; i < m; i++) { + while (j > 0 && pattern[i] != pattern[j]) { + j = next[j - 1]; + } + if (pattern[i] == pattern[j]) { + j++; + } + next[i] = j; + } + + for (int i = 0, j = 0; i < n; i++) { + while (j > 0 && text[i] != pattern[j]) { + j = next[j - 1]; + } + if (text[i] == pattern[j]) { + j++; + } + if (j == m) { + return i - m + 1; + } + } + return -1; +} \ No newline at end of file diff --git a/trick/primality-test.cpp b/trick/primality-test.cpp index e69de29..b565106 100644 --- a/trick/primality-test.cpp +++ b/trick/primality-test.cpp @@ -0,0 +1,17 @@ +#include + +bool primality_check(int n) { + std::vector is_prime(n + 1, true); + if (n <= 2) { + return false; + } + is_prime[0] = is_prime[1] = false; + for (int i = 2; i * i <= n; i++) { + if (is_prime[i]) { + for (int j = i * i; j <= n; j += i) { + is_prime[j] = false; + } + } + } + return is_prime[n]; +} \ No newline at end of file diff --git a/trick/quick-pow.cpp b/trick/quick-pow.cpp index e69de29..124e109 100644 --- a/trick/quick-pow.cpp +++ b/trick/quick-pow.cpp @@ -0,0 +1,11 @@ +long long quick_pow(int base, int power) { + long long ans = 1; + while (power > 0) { + if (power & 1) { + ans *= base; + } + base *= base; + power >>= 1; + } + return ans; +} \ No newline at end of file diff --git a/trick/split-text.cpp b/trick/split-text.cpp new file mode 100644 index 0000000..bed7006 --- /dev/null +++ b/trick/split-text.cpp @@ -0,0 +1,13 @@ +#include +#include + +std::vector split(std::string target, std::string pattern) { + std::vector res; + size_t start = 0, next = 0; + while ((next = target.find(pattern, start)) != std::string::npos) { + res.push_back(target.substr(start, next - start)); + start = next + pattern.length(); + } + res.push_back(target.substr(start)); + return res; +} \ No newline at end of file