Skip to content

Commit

Permalink
Merge branch 'master' into add/number_of_paths
Browse files Browse the repository at this point in the history
  • Loading branch information
adi776borate authored Oct 27, 2024
2 parents 12c94c1 + ecb8a33 commit ee6e56c
Show file tree
Hide file tree
Showing 5 changed files with 599 additions and 43 deletions.
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,7 @@
* [Sparse Table](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/range_queries/sparse_table.cpp)

## Search
* [Longest Increasing Subsequence Using Binary Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/search/Longest_Increasing_Subsequence_using_binary_search.cpp)
* [Binary Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/search/binary_search.cpp)
* [Exponential Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/search/exponential_search.cpp)
* [Fibonacci Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/search/fibonacci_search.cpp)
Expand Down
119 changes: 119 additions & 0 deletions greedy_algorithms/binary_addition.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
/**
* @file binary_addition.cpp
* @brief Adds two binary numbers and outputs resulting string
*
* @details The algorithm for adding two binary strings works by processing them
* from right to left, similar to manual addition. It starts by determining the
* longer string's length to ensure both strings are fully traversed. For each
* pair of corresponding bits and any carry from the previous addition, it
* calculates the sum. If the sum exceeds 1, a carry is generated for the next
* bit. The results for each bit are collected in a result string, which is
* reversed at the end to present the final binary sum correctly. Additionally,
* the function validates the input to ensure that only valid binary strings
* (containing only '0' and '1') are processed. If invalid input is detected,
* it returns an empty string.
* @author [Muhammad Junaid Khalid](https://github.com/mjk22071998)
*/

#include <algorithm> /// for reverse function
#include <cassert> /// for tests
#include <iostream> /// for input and outputs
#include <string> /// for string class

/**
* @namespace
* @brief Greedy Algorithms
*/
namespace greedy_algorithms {
/**
* @brief A class to perform binary addition of two binary strings.
*/
class BinaryAddition {
public:
/**
* @brief Adds two binary strings and returns the result as a binary string.
* @param a The first binary string.
* @param b The second binary string.
* @return The sum of the two binary strings as a binary string, or an empty
* string if either input string contains non-binary characters.
*/
std::string addBinary(const std::string& a, const std::string& b) {
if (!isValidBinaryString(a) || !isValidBinaryString(b)) {
return ""; // Return empty string if input contains non-binary
// characters
}

std::string result;
int carry = 0;
int maxLength = std::max(a.size(), b.size());

// Traverse both strings from the end to the beginning
for (int i = 0; i < maxLength; ++i) {
// Get the current bits from both strings, if available
int bitA = (i < a.size()) ? (a[a.size() - 1 - i] - '0') : 0;
int bitB = (i < b.size()) ? (b[b.size() - 1 - i] - '0') : 0;

// Calculate the sum of bits and carry
int sum = bitA + bitB + carry;
carry = sum / 2; // Determine the carry for the next bit
result.push_back((sum % 2) +
'0'); // Append the sum's current bit to result
}
if (carry) {
result.push_back('1');
}
std::reverse(result.begin(), result.end());
return result;
}

private:
/**
* @brief Validates whether a string contains only binary characters (0 or 1).
* @param str The string to validate.
* @return true if the string is binary, false otherwise.
*/
bool isValidBinaryString(const std::string& str) const {
return std::all_of(str.begin(), str.end(),
[](char c) { return c == '0' || c == '1'; });
}
};
} // namespace greedy_algorithms

/**
* @brief run self test implementation.
* @returns void
*/
static void tests() {
greedy_algorithms::BinaryAddition binaryAddition;

// Valid binary string tests
assert(binaryAddition.addBinary("1010", "1101") == "10111");
assert(binaryAddition.addBinary("1111", "1111") == "11110");
assert(binaryAddition.addBinary("101", "11") == "1000");
assert(binaryAddition.addBinary("0", "0") == "0");
assert(binaryAddition.addBinary("1111", "1111") == "11110");
assert(binaryAddition.addBinary("0", "10101") == "10101");
assert(binaryAddition.addBinary("10101", "0") == "10101");
assert(binaryAddition.addBinary("101010101010101010101010101010",
"110110110110110110110110110110") ==
"1100001100001100001100001100000");
assert(binaryAddition.addBinary("1", "11111111") == "100000000");
assert(binaryAddition.addBinary("10101010", "01010101") == "11111111");

// Invalid binary string tests (should return empty string)
assert(binaryAddition.addBinary("10102", "1101") == "");
assert(binaryAddition.addBinary("ABC", "1101") == "");
assert(binaryAddition.addBinary("1010", "1102") == "");
assert(binaryAddition.addBinary("111", "1x1") == "");
assert(binaryAddition.addBinary("1x1", "111") == "");
assert(binaryAddition.addBinary("1234", "1101") == "");
}

/**
* @brief main function
* @returns 0 on successful exit
*/
int main() {
tests(); /// To execute tests
return 0;
}
128 changes: 85 additions & 43 deletions math/modular_inverse_fermat_little_theorem.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@
* a^{m-2} &≡& a^{-1} \;\text{mod}\; m
* \f}
*
* We will find the exponent using binary exponentiation. Such that the
* algorithm works in \f$O(\log m)\f$ time.
* We will find the exponent using binary exponentiation such that the
* algorithm works in \f$O(\log n)\f$ time.
*
* Examples: -
* * a = 3 and m = 7
Expand All @@ -43,56 +43,98 @@
* (as \f$a\times a^{-1} = 1\f$)
*/

#include <iostream>
#include <vector>
#include <cassert> /// for assert
#include <cstdint> /// for std::int64_t
#include <iostream> /// for IO implementations

/** Recursive function to calculate exponent in \f$O(\log n)\f$ using binary
* exponent.
/**
* @namespace math
* @brief Maths algorithms.
*/
namespace math {
/**
* @namespace modular_inverse_fermat
* @brief Calculate modular inverse using Fermat's Little Theorem.
*/
namespace modular_inverse_fermat {
/**
* @brief Calculate exponent with modulo using binary exponentiation in \f$O(\log b)\f$ time.
* @param a The base
* @param b The exponent
* @param m The modulo
* @return The result of \f$a^{b} % m\f$
*/
int64_t binExpo(int64_t a, int64_t b, int64_t m) {
a %= m;
int64_t res = 1;
while (b > 0) {
if (b % 2) {
res = res * a % m;
}
a = a * a % m;
// Dividing b by 2 is similar to right shift.
b >>= 1;
std::int64_t binExpo(std::int64_t a, std::int64_t b, std::int64_t m) {
a %= m;
std::int64_t res = 1;
while (b > 0) {
if (b % 2 != 0) {
res = res * a % m;
}
return res;
a = a * a % m;
// Dividing b by 2 is similar to right shift by 1 bit
b >>= 1;
}
return res;
}

/** Prime check in \f$O(\sqrt{m})\f$ time.
/**
* @brief Check if an integer is a prime number in \f$O(\sqrt{m})\f$ time.
* @param m An intger to check for primality
* @return true if the number is prime
* @return false if the number is not prime
*/
bool isPrime(int64_t m) {
if (m <= 1) {
return false;
} else {
for (int64_t i = 2; i * i <= m; i++) {
if (m % i == 0) {
return false;
}
}
bool isPrime(std::int64_t m) {
if (m <= 1) {
return false;
}
for (std::int64_t i = 2; i * i <= m; i++) {
if (m % i == 0) {
return false;
}
return true;
}
return true;
}
/**
* @brief calculates the modular inverse.
* @param a Integer value for the base
* @param m Integer value for modulo
* @return The result that is the modular inverse of a modulo m
*/
std::int64_t modular_inverse(std::int64_t a, std::int64_t m) {
while (a < 0) {
a += m;
}

// Check for invalid cases
if (!isPrime(m) || a == 0) {
return -1; // Invalid input
}

return binExpo(a, m - 2, m); // Fermat's Little Theorem
}
} // namespace modular_inverse_fermat
} // namespace math

/**
* @brief Self-test implementation
* @return void
*/
static void test() {
assert(math::modular_inverse_fermat::modular_inverse(0, 97) == -1);
assert(math::modular_inverse_fermat::modular_inverse(15, -2) == -1);
assert(math::modular_inverse_fermat::modular_inverse(3, 10) == -1);
assert(math::modular_inverse_fermat::modular_inverse(3, 7) == 5);
assert(math::modular_inverse_fermat::modular_inverse(1, 101) == 1);
assert(math::modular_inverse_fermat::modular_inverse(-1337, 285179) == 165519);
assert(math::modular_inverse_fermat::modular_inverse(123456789, 998244353) == 25170271);
assert(math::modular_inverse_fermat::modular_inverse(-9876543210, 1000000007) == 784794281);
}

/**
* Main function
* @brief Main function
* @return 0 on exit
*/
int main() {
int64_t a, m;
// Take input of a and m.
std::cout << "Computing ((a^(-1))%(m)) using Fermat's Little Theorem";
std::cout << std::endl << std::endl;
std::cout << "Give input 'a' and 'm' space separated : ";
std::cin >> a >> m;
if (isPrime(m)) {
std::cout << "The modular inverse of a with mod m is (a^(m-2)) : ";
std::cout << binExpo(a, m - 2, m) << std::endl;
} else {
std::cout << "m must be a prime number.";
std::cout << std::endl;
}
test(); // run self-test implementation
return 0;
}
Loading

0 comments on commit ee6e56c

Please sign in to comment.