Skip to content

Commit ee6e56c

Browse files
authored
Merge branch 'master' into add/number_of_paths
2 parents 12c94c1 + ecb8a33 commit ee6e56c

File tree

5 files changed

+599
-43
lines changed

5 files changed

+599
-43
lines changed

DIRECTORY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,7 @@
340340
* [Sparse Table](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/range_queries/sparse_table.cpp)
341341

342342
## Search
343+
* [Longest Increasing Subsequence Using Binary Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/search/Longest_Increasing_Subsequence_using_binary_search.cpp)
343344
* [Binary Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/search/binary_search.cpp)
344345
* [Exponential Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/search/exponential_search.cpp)
345346
* [Fibonacci Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/search/fibonacci_search.cpp)

greedy_algorithms/binary_addition.cpp

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
/**
2+
* @file binary_addition.cpp
3+
* @brief Adds two binary numbers and outputs resulting string
4+
*
5+
* @details The algorithm for adding two binary strings works by processing them
6+
* from right to left, similar to manual addition. It starts by determining the
7+
* longer string's length to ensure both strings are fully traversed. For each
8+
* pair of corresponding bits and any carry from the previous addition, it
9+
* calculates the sum. If the sum exceeds 1, a carry is generated for the next
10+
* bit. The results for each bit are collected in a result string, which is
11+
* reversed at the end to present the final binary sum correctly. Additionally,
12+
* the function validates the input to ensure that only valid binary strings
13+
* (containing only '0' and '1') are processed. If invalid input is detected,
14+
* it returns an empty string.
15+
* @author [Muhammad Junaid Khalid](https://github.com/mjk22071998)
16+
*/
17+
18+
#include <algorithm> /// for reverse function
19+
#include <cassert> /// for tests
20+
#include <iostream> /// for input and outputs
21+
#include <string> /// for string class
22+
23+
/**
24+
* @namespace
25+
* @brief Greedy Algorithms
26+
*/
27+
namespace greedy_algorithms {
28+
/**
29+
* @brief A class to perform binary addition of two binary strings.
30+
*/
31+
class BinaryAddition {
32+
public:
33+
/**
34+
* @brief Adds two binary strings and returns the result as a binary string.
35+
* @param a The first binary string.
36+
* @param b The second binary string.
37+
* @return The sum of the two binary strings as a binary string, or an empty
38+
* string if either input string contains non-binary characters.
39+
*/
40+
std::string addBinary(const std::string& a, const std::string& b) {
41+
if (!isValidBinaryString(a) || !isValidBinaryString(b)) {
42+
return ""; // Return empty string if input contains non-binary
43+
// characters
44+
}
45+
46+
std::string result;
47+
int carry = 0;
48+
int maxLength = std::max(a.size(), b.size());
49+
50+
// Traverse both strings from the end to the beginning
51+
for (int i = 0; i < maxLength; ++i) {
52+
// Get the current bits from both strings, if available
53+
int bitA = (i < a.size()) ? (a[a.size() - 1 - i] - '0') : 0;
54+
int bitB = (i < b.size()) ? (b[b.size() - 1 - i] - '0') : 0;
55+
56+
// Calculate the sum of bits and carry
57+
int sum = bitA + bitB + carry;
58+
carry = sum / 2; // Determine the carry for the next bit
59+
result.push_back((sum % 2) +
60+
'0'); // Append the sum's current bit to result
61+
}
62+
if (carry) {
63+
result.push_back('1');
64+
}
65+
std::reverse(result.begin(), result.end());
66+
return result;
67+
}
68+
69+
private:
70+
/**
71+
* @brief Validates whether a string contains only binary characters (0 or 1).
72+
* @param str The string to validate.
73+
* @return true if the string is binary, false otherwise.
74+
*/
75+
bool isValidBinaryString(const std::string& str) const {
76+
return std::all_of(str.begin(), str.end(),
77+
[](char c) { return c == '0' || c == '1'; });
78+
}
79+
};
80+
} // namespace greedy_algorithms
81+
82+
/**
83+
* @brief run self test implementation.
84+
* @returns void
85+
*/
86+
static void tests() {
87+
greedy_algorithms::BinaryAddition binaryAddition;
88+
89+
// Valid binary string tests
90+
assert(binaryAddition.addBinary("1010", "1101") == "10111");
91+
assert(binaryAddition.addBinary("1111", "1111") == "11110");
92+
assert(binaryAddition.addBinary("101", "11") == "1000");
93+
assert(binaryAddition.addBinary("0", "0") == "0");
94+
assert(binaryAddition.addBinary("1111", "1111") == "11110");
95+
assert(binaryAddition.addBinary("0", "10101") == "10101");
96+
assert(binaryAddition.addBinary("10101", "0") == "10101");
97+
assert(binaryAddition.addBinary("101010101010101010101010101010",
98+
"110110110110110110110110110110") ==
99+
"1100001100001100001100001100000");
100+
assert(binaryAddition.addBinary("1", "11111111") == "100000000");
101+
assert(binaryAddition.addBinary("10101010", "01010101") == "11111111");
102+
103+
// Invalid binary string tests (should return empty string)
104+
assert(binaryAddition.addBinary("10102", "1101") == "");
105+
assert(binaryAddition.addBinary("ABC", "1101") == "");
106+
assert(binaryAddition.addBinary("1010", "1102") == "");
107+
assert(binaryAddition.addBinary("111", "1x1") == "");
108+
assert(binaryAddition.addBinary("1x1", "111") == "");
109+
assert(binaryAddition.addBinary("1234", "1101") == "");
110+
}
111+
112+
/**
113+
* @brief main function
114+
* @returns 0 on successful exit
115+
*/
116+
int main() {
117+
tests(); /// To execute tests
118+
return 0;
119+
}

math/modular_inverse_fermat_little_theorem.cpp

Lines changed: 85 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,8 @@
3030
* a^{m-2} &≡& a^{-1} \;\text{mod}\; m
3131
* \f}
3232
*
33-
* We will find the exponent using binary exponentiation. Such that the
34-
* algorithm works in \f$O(\log m)\f$ time.
33+
* We will find the exponent using binary exponentiation such that the
34+
* algorithm works in \f$O(\log n)\f$ time.
3535
*
3636
* Examples: -
3737
* * a = 3 and m = 7
@@ -43,56 +43,98 @@
4343
* (as \f$a\times a^{-1} = 1\f$)
4444
*/
4545

46-
#include <iostream>
47-
#include <vector>
46+
#include <cassert> /// for assert
47+
#include <cstdint> /// for std::int64_t
48+
#include <iostream> /// for IO implementations
4849

49-
/** Recursive function to calculate exponent in \f$O(\log n)\f$ using binary
50-
* exponent.
50+
/**
51+
* @namespace math
52+
* @brief Maths algorithms.
53+
*/
54+
namespace math {
55+
/**
56+
* @namespace modular_inverse_fermat
57+
* @brief Calculate modular inverse using Fermat's Little Theorem.
58+
*/
59+
namespace modular_inverse_fermat {
60+
/**
61+
* @brief Calculate exponent with modulo using binary exponentiation in \f$O(\log b)\f$ time.
62+
* @param a The base
63+
* @param b The exponent
64+
* @param m The modulo
65+
* @return The result of \f$a^{b} % m\f$
5166
*/
52-
int64_t binExpo(int64_t a, int64_t b, int64_t m) {
53-
a %= m;
54-
int64_t res = 1;
55-
while (b > 0) {
56-
if (b % 2) {
57-
res = res * a % m;
58-
}
59-
a = a * a % m;
60-
// Dividing b by 2 is similar to right shift.
61-
b >>= 1;
67+
std::int64_t binExpo(std::int64_t a, std::int64_t b, std::int64_t m) {
68+
a %= m;
69+
std::int64_t res = 1;
70+
while (b > 0) {
71+
if (b % 2 != 0) {
72+
res = res * a % m;
6273
}
63-
return res;
74+
a = a * a % m;
75+
// Dividing b by 2 is similar to right shift by 1 bit
76+
b >>= 1;
77+
}
78+
return res;
6479
}
65-
66-
/** Prime check in \f$O(\sqrt{m})\f$ time.
80+
/**
81+
* @brief Check if an integer is a prime number in \f$O(\sqrt{m})\f$ time.
82+
* @param m An intger to check for primality
83+
* @return true if the number is prime
84+
* @return false if the number is not prime
6785
*/
68-
bool isPrime(int64_t m) {
69-
if (m <= 1) {
70-
return false;
71-
} else {
72-
for (int64_t i = 2; i * i <= m; i++) {
73-
if (m % i == 0) {
74-
return false;
75-
}
76-
}
86+
bool isPrime(std::int64_t m) {
87+
if (m <= 1) {
88+
return false;
89+
}
90+
for (std::int64_t i = 2; i * i <= m; i++) {
91+
if (m % i == 0) {
92+
return false;
7793
}
78-
return true;
94+
}
95+
return true;
96+
}
97+
/**
98+
* @brief calculates the modular inverse.
99+
* @param a Integer value for the base
100+
* @param m Integer value for modulo
101+
* @return The result that is the modular inverse of a modulo m
102+
*/
103+
std::int64_t modular_inverse(std::int64_t a, std::int64_t m) {
104+
while (a < 0) {
105+
a += m;
106+
}
107+
108+
// Check for invalid cases
109+
if (!isPrime(m) || a == 0) {
110+
return -1; // Invalid input
111+
}
112+
113+
return binExpo(a, m - 2, m); // Fermat's Little Theorem
114+
}
115+
} // namespace modular_inverse_fermat
116+
} // namespace math
117+
118+
/**
119+
* @brief Self-test implementation
120+
* @return void
121+
*/
122+
static void test() {
123+
assert(math::modular_inverse_fermat::modular_inverse(0, 97) == -1);
124+
assert(math::modular_inverse_fermat::modular_inverse(15, -2) == -1);
125+
assert(math::modular_inverse_fermat::modular_inverse(3, 10) == -1);
126+
assert(math::modular_inverse_fermat::modular_inverse(3, 7) == 5);
127+
assert(math::modular_inverse_fermat::modular_inverse(1, 101) == 1);
128+
assert(math::modular_inverse_fermat::modular_inverse(-1337, 285179) == 165519);
129+
assert(math::modular_inverse_fermat::modular_inverse(123456789, 998244353) == 25170271);
130+
assert(math::modular_inverse_fermat::modular_inverse(-9876543210, 1000000007) == 784794281);
79131
}
80132

81133
/**
82-
* Main function
134+
* @brief Main function
135+
* @return 0 on exit
83136
*/
84137
int main() {
85-
int64_t a, m;
86-
// Take input of a and m.
87-
std::cout << "Computing ((a^(-1))%(m)) using Fermat's Little Theorem";
88-
std::cout << std::endl << std::endl;
89-
std::cout << "Give input 'a' and 'm' space separated : ";
90-
std::cin >> a >> m;
91-
if (isPrime(m)) {
92-
std::cout << "The modular inverse of a with mod m is (a^(m-2)) : ";
93-
std::cout << binExpo(a, m - 2, m) << std::endl;
94-
} else {
95-
std::cout << "m must be a prime number.";
96-
std::cout << std::endl;
97-
}
138+
test(); // run self-test implementation
139+
return 0;
98140
}

0 commit comments

Comments
 (0)